﻿using System;
using System.Data;
using System.Configuration;
//using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
//using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
using System.Globalization;
using System.Collections;

/// <summary>
/// Descripción breve de DB
/// </summary>
public class DB
{
    private string _wheredb = "";
    public DB()
    {

        //
        // TODO: Agregar aquí la lógica del constructor
        //
    }

    public static SqlConnection OpenConnection()
    {
        SqlConnection cnn = null;
        try
        {
            cnn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=BPOphotos;Integrated Security=True;Pooling=False");
            cnn.Open();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return cnn;
    }


    public static SqlConnection OpenConnection2()
    {
        SqlConnection cnn = null;
        try
        {
            cnn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=usuarios;Integrated Security=True;Pooling=False");
            cnn.Open();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return cnn;
    }


    public static DataSet getStatus(string perfilid)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Path");
        result.Tables["Tabla"].Columns.Add("estado_id");
        result.Tables["Tabla"].Columns.Add("Status");
        result.Tables["Tabla"].Columns.Add("Color");
        result.Tables["Tabla"].Columns.Add("Conteo");


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (perfilid.ToUpper().Equals("ADMIN"))
            {
                comm.CommandText = "SELECT  STATUS.path, STATUS.status_id, STATUS.name, STATUS.color FROM STATUS";
            }
            else
            {
                comm.CommandText = "SELECT  STATUS.path, STATUS.status_id, STATUS.name, STATUS.color FROM STATUS WHERE STATUS.name<>'paid'";
            }

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC4 = reader.GetString(0);//path
                if (!reader.IsDBNull(1)) rgb.intC1 = reader.GetInt32(1);//estadid
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//status
                if (!reader.IsDBNull(3)) rgb.strC3 = reader.GetString(3);//color
                rgb.strC5 = getStatusCount(rgb.intC1.ToString());//conteo


                object[] objArr = { rgb.strC4, rgb.intC1, rgb.strC2, rgb.strC3, rgb.strC5, };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }

    private static string getStatusCount(string statusid)
    {
        string result = "0";
        try
        {
            SqlConnection conn = null;

            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select count(order_id)as count from [ORDER] where status_id = " + statusid;
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "state");
            dt = ds.Tables["state"];
            if (dt.Rows.Count == 0)
            {
                result = "0";
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = fila["count"].ToString();
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = "0";

        }
        return result;
    }
    // si tiene direccion donde recoger
    public static int hasOptional(string par)
    {
        int result = 0;


        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select address from product where name='" + par + "'";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "product");
            dt = ds.Tables["product"];
            if (dt.Rows.Count == 0)
            {
                result = 0;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    if (int.Parse(fila["address"].ToString()) == 1)
                    {
                        result = 1;
                    }
                    else
                    {
                        result = 0;
                    }


                }
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = -1;

        }
        return result;


    }

    public static int getNextOrderId()
    {

        int result = 0;


        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select top 1 order_id from [ORDER] order by 1 desc";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "order");
            dt = ds.Tables["order"];
            if (dt.Rows.Count == 0)
            {
                result = 1;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila["order_id"].ToString()) + 1;
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = -1;

        }
        return result;

    }

    public static RE_GenericBean getOrden(int par)
    {


        RE_GenericBean rgb = new RE_GenericBean();
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;
            string select = "SELECT   [ORDER].ordernum, [ORDER].product_id, [ORDER].client_id, convert(varchar, [ORDER].duedate,101), convert(varchar, [ORDER].duetime, 108), [ORDER].comments, [ORDER].stnum, [ORDER].stadd,[ORDER].stcity, STATE.name AS Expr2, [ORDER].zip, STATUS.name AS Expr3, [ORDER].ord_date, [ORDER].ord_time, [ORDER].opstnum,[ORDER].opstadd, [ORDER].opcity, [ORDER].opstate, [ORDER].opzip, PRODUCT.address, COUNTY.name AS Expr1, [ORDER].fee, PRODUCT.vendor_fee, [ORDER].account, [ORDER].company, [ORDER].specialatttributes, [ORDER].psfprice, [ORDER].appdate, upper([ORDER].appcomments), upper([ORDER].contactinfo), upper([ORDER].appcoordinator), upper([ORDER].appoutcome), upper([ORDER].appt), [ORDER].ord_failed,[ORDER].ord_receivephotos, [ORDER].ord_completeset, [ORDER].ord_exterioronly, [ORDER].ord_uploadby, convert(varchar, [ORDER].ord_upload_date, 101), convert(varchar, [ORDER].ord_upload_time, 108),  upper([ORDER].apptime), [ORDER].ord_cancelled, (case WHEN [ORDER].driver_fee IS NULL THEN -1 ELSE [ORDER].driver_fee END), [ORDER].damages,  ofail.fail_id, [ORDER].ord_rv, [ORDER].ord_drvcomment, [ORDER].ord_rv_by, convert(varchar, [ORDER].ord_rv_date,101), convert(varchar, [ORDER].ord_rv_time, 108), [ORDER].ord_driver_ext, [ORDER].ord_driver_ext_date, [ORDER].paid, convert(varchar, [ORDER].ord_driver_date,101), convert(varchar, [ORDER].ord_driver_time, 108), [ORDER].unit  ";
            string strsql = select + " FROM [ORDER] INNER JOIN PRODUCT ON [ORDER].product_id = PRODUCT.product_id INNER JOIN STATE ON [ORDER].state = STATE.state_id INNER JOIN STATUS ON [ORDER].status_id = STATUS.status_id INNER JOIN COUNTY ON [ORDER].county = COUNTY.county_id AND STATE.state_id = COUNTY.state_id  LEFT OUTER JOIN  ( Select  OA.order_id, OA.fail_id  from ORDER_FAIL as OA, ( SELECT  order_id, MAX(order_fail_id) as order_fail_id FROM  ORDER_FAIL   group by order_id ) as tabla where tabla.order_fail_id = OA.order_fail_id ) AS ofail ON [ORDER].order_id = ofail.order_id WHERE     ([ORDER].order_id = " + par + ")";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "order");
            dt = ds.Tables["order"];
            if (dt.Rows.Count == 0)
            {
                return rgb;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    if (fila[0] != null) rgb.strC39 = fila[0].ToString();  //orden_#
                    if (fila[1] != null) rgb.strC1 = fila[1].ToString(); //product_id name
                    if (fila[2] != null) rgb.strC31 = (fila[2].ToString()); //client_id
                    if (fila[3] != null) rgb.strC2 = fila[3].ToString(); //duedate
                    if (fila[4] != null) rgb.strC3 = fila[4].ToString(); //duetime
                    if (fila[5] != null) rgb.strC4 = fila[5].ToString();//comments
                    if (fila[6] != null) rgb.strC5 = fila[6].ToString();//stnum
                    if (fila[7] != null) rgb.strC6 = fila[7].ToString();//stadd
                    if (fila[8] != null) rgb.strC7 = fila[8].ToString();//stcity
                    if (fila[9] != null) rgb.strC8 = fila[9].ToString();//state
                    if (fila[10] != null) rgb.strC9 = fila[10].ToString();//zip
                    if (fila[11] != null) rgb.strC10 = fila[11].ToString();//status
                    if (fila[12] != null) rgb.strC11 = fila[12].ToString();//ord_date
                    if (fila[13] != null) rgb.strC12 = fila[13].ToString();//ord_time
                    if (fila[14] != null) rgb.strC13 = fila[14].ToString();//opstnum
                    if (fila[15] != null) rgb.strC14 = fila[15].ToString();//opstadd
                    if (fila[16] != null) rgb.strC15 = fila[16].ToString();//opcity
                    if (fila[17] != null) rgb.strC16 = fila[17].ToString();//opstate
                    if (fila[18] != null) rgb.strC17 = fila[18].ToString();//opzip
                    if (fila[19] != null) rgb.intC4 = int.Parse(fila[19].ToString());//product.address if have opt
                    if (fila[20] != null) rgb.strC18 = fila[20].ToString();//county
                    if (fila[21] != null) rgb.strC20 = fila[21].ToString(); //TotalFee-fee
                    if (fila[22] != null) rgb.strC21 = fila[22].ToString(); //vendor_fee
                    if (fila[23] != null) rgb.strC22 = fila[23].ToString(); //account
                    if (fila[24] != null) rgb.strC23 = fila[24].ToString(); //company
                    if (fila[25] != null) rgb.strC24 = fila[25].ToString(); //specialAttributes
                    if (fila[26] != null) rgb.strC25 = fila[26].ToString(); //psfprice
                    if (fila[27] != null) rgb.strC26 = fila[27].ToString(); //appdate
                    if (fila[28] != null) rgb.strC27 = fila[28].ToString(); //appcomment
                    if (fila[29] != null) rgb.strC28 = fila[29].ToString(); //contacinfo
                    if (fila[30] != null) rgb.strC29 = fila[30].ToString(); //appcoordinator
                    if (fila[31] != null) rgb.strC30 = fila[31].ToString(); //appoutcome

                    //31 ya lo tiene client_id
                    if (fila[32] != null)
                    {
                        string p = fila[32].ToString();
                        rgb.intC5 = 0;

                        if (p == "1") { rgb.intC5 = 1; }

                    } //appt bandera
                    if (fila[33] != null) rgb.strC32 = fila[33].ToString(); //ord_failed
                    if (fila[34] != null) rgb.strC33 = fila[34].ToString(); //ord_receivephotos
                    if (fila[35] != null) rgb.strC34 = fila[35].ToString(); //ord_completeset
                    if (fila[36] != null) rgb.strC35 = fila[36].ToString(); //ord_exterioroly
                    if (fila[37] != null) rgb.strC36 = fila[37].ToString(); //ord_uploadby
                    if (fila[38] != null) rgb.strC37 = fila[38].ToString(); //ord_upload_date
                    if (fila[39] != null) rgb.strC38 = fila[39].ToString(); //ord_upload_time
                    if (fila[40] != null) rgb.strC40 = fila[40].ToString(); //apptime
                    if (fila[41] != null) rgb.strC41 = fila[41].ToString();//ord_cancelled
                    string cadena = "";
                    if (fila[42] != null) cadena = fila[42].ToString();//driver_fee
                    if (!cadena.Equals("")) { rgb.doubleC1 = double.Parse(cadena); }
                    if (fila[43] != null) rgb.strC42 = fila[43].ToString();//ord damages
                    if (fila[44] != null) cadena = fila[44].ToString();//[ord_fail].fail_id
                    if (!cadena.Equals("")) { rgb.intC6 = int.Parse(cadena); } else { rgb.intC6 = -1; }
                    if (fila[45] != null) rgb.strC43 = fila[45].ToString();//ord_rv
                    if (fila[46] != null) rgb.strC44 = fila[46].ToString();//ord_drvcomment
                    if (fila[47] != null) rgb.strC45 = fila[47].ToString();//ord_rv_by
                    if (fila[48] != null) rgb.strC46 = fila[48].ToString();//ord_rv_date
                    if (fila[49] != null) rgb.strC47 = fila[49].ToString();//ord_rv_time
                    if (fila[50] != null) rgb.strC48 = fila[50].ToString();//ord_driver_ext
                    if (fila[51] != null) rgb.strC49 = fila[51].ToString();//ord_driver_ext_date
                    if (fila[52] != null) rgb.strC50 = fila[52].ToString();// Paid
                    if (fila[53] != null) rgb.strC51 = fila[53].ToString(); //ord_driver_date
                    if (fila[54] != null) rgb.strC52 = fila[54].ToString(); //ord_driver_time
                    if (fila[55] != null) rgb.strC53 = fila[55].ToString(); //unit
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            return null;

        }


        return rgb;


    }

    public static DataSet GetOrders(long permisowk, long permisoDet, string filterstatus, string filtroorden, string usinitial, string pwhere, string pwhere2, string pwhere3, int busqueda, int perfilID)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("damages");//0 photos damages
        result.Tables["Tabla"].Columns.Add("Order #");//1
        result.Tables["Tabla"].Columns.Add("Due Date");//2
        result.Tables["Tabla"].Columns.Add("Due Time");//3
        result.Tables["Tabla"].Columns.Add("Client");//4
        result.Tables["Tabla"].Columns.Add("Company");//5
        result.Tables["Tabla"].Columns.Add("Account");//6
        result.Tables["Tabla"].Columns.Add("Type");//7
        result.Tables["Tabla"].Columns.Add("Street No.");//8
        result.Tables["Tabla"].Columns.Add("Street Address");//9
        result.Tables["Tabla"].Columns.Add("City");//10
        result.Tables["Tabla"].Columns.Add("State");//11
        result.Tables["Tabla"].Columns.Add("County");//12
        result.Tables["Tabla"].Columns.Add("Zip");//13
        result.Tables["Tabla"].Columns.Add("Proc");//14
        result.Tables["Tabla"].Columns.Add("Drv");//15
        result.Tables["Tabla"].Columns.Add("ord_qc");//16
        result.Tables["Tabla"].Columns.Add("PI Comments");//17
        result.Tables["Tabla"].Columns.Add("POC Comments");//18
        result.Tables["Tabla"].Columns.Add("Status");//19
        result.Tables["Tabla"].Columns.Add("Appt");//20
        result.Tables["Tabla"].Columns.Add("Apptime");//21
        result.Tables["Tabla"].Columns.Add("Appt Comments");//22
        result.Tables["Tabla"].Columns.Add("Drv. Comments");//23
        result.Tables["Tabla"].Columns.Add("specialatttributes");//24 special
        result.Tables["Tabla"].Columns.Add("ord_failed");//25 yes o no
        result.Tables["Tabla"].Columns.Add("ord_failed_id");//26 ord_failed_id
        result.Tables["Tabla"].Columns.Add("ord_processor_done");//27 yes o no
        result.Tables["Tabla"].Columns.Add("ord_driver_done");//28 yes o no
        result.Tables["Tabla"].Columns.Add("ord_qc_done");//29 yes o no
        result.Tables["Tabla"].Columns.Add("Order id");//30
        result.Tables["Tabla"].Columns.Add("ord_rv");//31 yes o no
        result.Tables["Tabla"].Columns.Add("Indice");//32 indice
        result.Tables["Tabla"].Columns.Add("Paid");//33 Paid

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            string where = "";

            string orderby;
            string from;
            long testpermiso = (permisoDet & 4); //SeePaid
            long testpermiso2 = (permisowk & 4); //View All Orders
            long testperuser = (permisoDet & 4);//SeePaid
            long testperuser2 = (permisowk & 4); //View All Orders

            long pdriver = (permisowk & 64); //Drv information
            string selectDB = "";

            //selectDB = "SELECT  [ORDER].damages, [ORDER].ordernum, CONVERT(varchar, [ORDER].duedate, 101) duedate, CONVERT (varchar, [ORDER].duetime,108) duetime, [ORDER].client_id, [ORDER].company, [ORDER].account, upper(PRODUCT.initial) product, upper([ORDER].stnum) stnum,  case when ([ORDER].unit is null or [ORDER].unit= '' ) then upper([ORDER].stadd) else upper([ORDER].stadd+' # '+[ORDER].unit)  end  stadd, upper([ORDER].stcity) stcity, upper(STATE.initial) state, upper(COUNTY.initial) AS  county, [ORDER].zip, upper( CASE WHEN [ORDER].product_id =  1 THEN 'N/A' WHEN [ORDER].product_id = 2 THEN 'N/A'  WHEN [ORDER].product_id = 8 THEN 'N/A' WHEN [ORDER].product_id = 10 THEN 'N/A' WHEN [ORDER].product_id = 13 THEN 'N/A' ELSE [ORDER].ord_processor END  ) ord_processor, upper(   (CASE WHEN ([ORDER].product_id = 3 and [ORDER].client_id = 'FIVESTAR' ) THEN 'FS' WHEN ([ORDER].product_id = 3 and [ORDER].client_id <> 'FIVESTAR' ) THEN 'N/A' WHEN ([ORDER].product_id = 4  and [ORDER].client_id = 'FIVESTAR') THEN 'FS' WHEN ([ORDER].product_id = 4  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A' WHEN ([ORDER].product_id = 5  and [ORDER].client_id = 'FIVESTAR') THEN 'FS' WHEN ([ORDER].product_id = 5  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A'  WHEN ([ORDER].product_id = 10  and [ORDER].client_id = 'FIVESTAR') THEN 'FS' WHEN ([ORDER].product_id = 10  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A' WHEN ([ORDER].product_id = 11  and [ORDER].client_id = 'FIVESTAR') THEN 'FS' WHEN ([ORDER].product_id = 11  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A'  ELSE  ord_driver END)  ) ord_driver, [ORDER].ord_qc as qc, [ORDER].comments, upper([ORDER].contactinfo) as contactinfo, upper(STATUS.name) status, [ORDER].appdate, upper([ORDER].apptime) apptime, upper([ORDER].appcomments) appcomments, upper([ORDER].ord_drvcomment) as drvcomments, [ORDER].specialatttributes, upper([ORDER].ord_failed) ord_failed, [ORDER].ord_failed_id, upper( (CASE WHEN [ORDER].product_id = 1 THEN 'N/A' WHEN [ORDER].product_id = 2 THEN 'N/A' WHEN [ORDER].product_id = 8 THEN 'N/A' WHEN [ORDER].product_id = 10 THEN 'N/A' WHEN [ORDER].product_id = 13 THEN 'N/A' ELSE ord_processor_done END)  ) ord_processor_done, upper( (CASE WHEN ([ORDER].product_id = 3 and [ORDER].client_id = 'FIVESTAR' ) THEN ord_driver_done WHEN ([ORDER].product_id = 3 and [ORDER].client_id <> 'FIVESTAR' ) THEN 'N/A' WHEN ([ORDER].product_id = 4  and [ORDER].client_id = 'FIVESTAR') THEN ord_driver_done WHEN ([ORDER].product_id = 4  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A' WHEN ([ORDER].product_id = 5  and [ORDER].client_id = 'FIVESTAR') THEN ord_driver_done WHEN ([ORDER].product_id = 5  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A'  WHEN ([ORDER].product_id = 10  and [ORDER].client_id = 'FIVESTAR') THEN ord_driver_done WHEN ([ORDER].product_id = 10  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A' WHEN ([ORDER].product_id = 11  and [ORDER].client_id = 'FIVESTAR') THEN ord_driver_done WHEN ([ORDER].product_id = 11  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A'  ELSE  ord_driver_done END)  ) ord_driver_done, [ORDER].ord_qc_done, [ORDER].order_id, [ORDER].ord_rv, [ORDER].ord_sector ";
            selectDB = "SELECT  [ORDER].damages, [ORDER].ordernum, CONVERT(varchar, [ORDER].duedate, 101) duedate, CONVERT (varchar, [ORDER].duetime,108) duetime, [ORDER].client_id, [ORDER].company, [ORDER].account, upper(PRODUCT.initial) product, upper([ORDER].stnum) stnum,  case when ([ORDER].unit is null or [ORDER].unit= '' ) then upper([ORDER].stadd) else upper([ORDER].stadd+' # '+[ORDER].unit)  end  stadd, upper([ORDER].stcity) stcity, upper(STATE.initial) state, upper(COUNTY.initial) AS  county, [ORDER].zip, upper( CASE WHEN [ORDER].product_id in ( 1,2,8,13,15,16,10 ) THEN 'N/A'  ELSE [ORDER].ord_processor END  ) ord_processor, upper(   (CASE WHEN ([ORDER].product_id = 3 and [ORDER].client_id = 'FIVESTAR' ) THEN 'FS' WHEN ([ORDER].product_id = 3 and [ORDER].client_id <> 'FIVESTAR' ) THEN 'N/A' WHEN ([ORDER].product_id = 4  and [ORDER].client_id = 'FIVESTAR') THEN 'FS' WHEN ([ORDER].product_id = 4  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A' WHEN ([ORDER].product_id = 5  and [ORDER].client_id = 'FIVESTAR') THEN 'FS' WHEN ([ORDER].product_id = 5  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A'  WHEN ([ORDER].product_id = 10  and [ORDER].client_id = 'FIVESTAR') THEN 'FS' WHEN ([ORDER].product_id = 10  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A' WHEN ([ORDER].product_id = 11  and [ORDER].client_id = 'FIVESTAR') THEN 'FS' WHEN ([ORDER].product_id = 11  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A'  ELSE  ord_driver END)  ) ord_driver, [ORDER].ord_qc as qc, [ORDER].comments, upper([ORDER].contactinfo) as contactinfo, upper(STATUS.name) status, [ORDER].appdate, upper([ORDER].apptime) apptime, upper([ORDER].appcomments) appcomments, upper([ORDER].ord_drvcomment) as drvcomments, [ORDER].specialatttributes, upper([ORDER].ord_failed) ord_failed, [ORDER].ord_failed_id, upper( (CASE WHEN [ORDER].product_id in( 1,2,8,10,13,15,16 )THEN 'N/A'  ELSE ord_processor_done END)  ) ord_processor_done, upper( (CASE WHEN ([ORDER].product_id = 3 and [ORDER].client_id = 'FIVESTAR' ) THEN ord_driver_done WHEN ([ORDER].product_id = 3 and [ORDER].client_id <> 'FIVESTAR' ) THEN 'N/A' WHEN ([ORDER].product_id = 4  and [ORDER].client_id = 'FIVESTAR') THEN ord_driver_done WHEN ([ORDER].product_id = 4  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A' WHEN ([ORDER].product_id = 5  and [ORDER].client_id = 'FIVESTAR') THEN ord_driver_done WHEN ([ORDER].product_id = 5  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A'  WHEN ([ORDER].product_id = 10  and [ORDER].client_id = 'FIVESTAR') THEN ord_driver_done WHEN ([ORDER].product_id = 10  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A' WHEN ([ORDER].product_id = 11  and [ORDER].client_id = 'FIVESTAR') THEN ord_driver_done WHEN ([ORDER].product_id = 11  and [ORDER].client_id <> 'FIVESTAR') THEN 'N/A'  ELSE  ord_driver_done END)  ) ord_driver_done, [ORDER].ord_qc_done, [ORDER].order_id, [ORDER].ord_rv, [ORDER].ord_sector ";


            from = " FROM  [ORDER] INNER JOIN COUNTY ON [ORDER].county = COUNTY.county_id INNER JOIN  STATE ON [ORDER].state = STATE.state_id AND COUNTY.state_id = STATE.state_id INNER JOIN STATUS ON [ORDER].status_id = STATUS.status_id INNER JOIN PRODUCT ON [ORDER].product_id = PRODUCT.product_id ";
            if (!filterstatus.Equals("all"))
            {

                if (filterstatus.ToUpper().Equals("DEFAULT"))
                {
                    if (testpermiso == 8 || testperuser == 8)
                    {
                        where = "  WHERE (Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN')";
                        //where = "  WHERE Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN' ";
                    }
                    else
                    {
                        where = " WHERE (Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN') and (Upper(STATUS.name) <>'PAID')  ";
                        // where = " WHERE Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN' and Upper(STATUS.name) <>'PAID'  ";
                    }

                }
                else if (filterstatus.ToUpper().Equals("ALLPENDING"))
                {
                    if (testpermiso == 4)
                    {
                        where = "  WHERE (Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN')";
                        //where = "  WHERE Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN' ";
                    }
                    else
                    {
                        where = " WHERE (Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN') and (Upper(STATUS.name) <>'PAID')  ";
                        // where = " WHERE Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN' and Upper(STATUS.name) <>'PAID'  ";
                    }
                }
                else if (filterstatus.ToUpper().Equals("PROCESSED"))
                {

                    where = " where (orden.ord_processor_done ='YES' or orden.ord_processor_done = 'N/A') and (orden.ord_failed is null or orden.ord_failed = 'NO') and (orden.ord_driver_done ='NO' or orden.ord_driver_done is null) and UPPER(orden.status)='PENDING' ";

                }
                else if (filterstatus.ToUpper().Equals("READY"))
                {
                    where = " WHERE Upper(orden.status)='PENDING' and ((orden.ord_driver_done='YES' and orden.ord_processor_done='YES') or (orden.ord_driver_done='YES' and orden.ord_processor_done='N/A') or (orden.ord_driver_done='N/A' and orden.ord_processor_done='YES') or (orden.ord_driver_done='N/A' and orden.ord_processor_done='N/A')) and  (orden.ord_failed is null or orden.ord_failed = 'NO') ";

                }
                else if (filterstatus.ToUpper().Equals("UNASSIGNED"))
                {
                    where = "  WHERE (orden.ord_processor = '' OR  orden.ord_processor IS NULL) and Upper(orden.status)='PENDING'  ";

                }
                else if (filterstatus.ToUpper().Equals("ASSIGNED"))
                {
                    where = " where  (orden.ord_processor <> '' and orden.ord_processor is not null) and (ord_processor_done = 'NO' OR ord_processor_done IS NULL)  and   UPPER(orden.status)='PENDING'  and (orden.ord_failed='NO' or orden.ord_failed is null ) ";

                }
                else if (filterstatus.ToUpper().Equals("UNASSIGNEDPHOTOS"))
                {
                    where = "  WHERE (orden.ord_driver = '' OR  orden.ord_driver IS NULL) and Upper(orden.status)='PENDING'  ";
                }
                else if (filterstatus.ToUpper().Equals("ASSIGNEDPHOTOS"))
                {
                    where = " where  (orden.ord_driver <> '' and orden.ord_driver is not null) and (ord_driver_done = 'NO' OR ord_driver_done IS NULL)  and   UPPER(orden.status)='PENDING'  and (orden.ord_failed='NO' or orden.ord_failed is null ) ";

                }
                else if (filterstatus.ToUpper().Equals("PROCESSEDPHOTOS"))
                {
                    where = " where (orden.ord_driver_done ='YES' or orden.ord_driver_done = 'N/A') and (orden.ord_processor_done ='NO' or orden.ord_processor_done is null) and (orden.ord_failed is null or orden.ord_failed = 'NO') and UPPER(orden.status)='PENDING' ";
                }
                else if (filterstatus.ToUpper().Equals("PHOTOS"))
                {
                    where = " where (orden.ord_failed is null or orden.ord_failed = 'NO') and (orden.ord_driver_done ='YES' or orden.ord_driver_done= 'N/A') and UPPER(orden.status)='PENDING' and orden.company<>1 ";
                }
                else if (filterstatus.ToUpper().Equals("BPOPHOTOS"))
                {
                    where = " where  UPPER(STATUS.name)='PENDING' and company=1 ";
                }
                else if (filterstatus.ToUpper().Equals("FAIL"))
                {
                    where = " WHERE   ( ord_failed = 'YES') and upper(STATUS.name)= 'PENDING' ";

                }
                else if (filterstatus.ToUpper().Equals("PACIFIC"))
                {
                    where = " WHERE   ( company<>1) and upper(STATUS.name)= 'PENDING' ";

                }

                else if (filterstatus.ToUpper().Equals("PROCESSEDC"))
                {
                    where = " where (orden.ord_failed is null or orden.ord_failed = 'NO') and (orden.ord_processor_done ='YES' or orden.ord_processor_done= 'N/A') and UPPER(orden.status)='PENDING' ";
                }

                else
                {
                    if (testpermiso == 4 || testperuser == 4)
                    {
                        where = "  WHERE Upper(STATUS.name)='" + filterstatus + "'";
                    }
                    else
                    {
                        if (filterstatus.ToUpper().Equals("PAID"))
                        {
                            where = " WHERE (STATUS.name='" + filterstatus + "')";
                        }
                        else
                        {
                            where = " WHERE ( STATUS.name='" + filterstatus + "' and Upper(STATUS.name) <>'PAID') ";

                        }
                    }
                }
                if (!filtroorden.Equals(""))
                {
                    where = where + " and [ORDER].ordernum like '%" + filtroorden + "%'";
                    comm.Parameters.Add("@order", SqlDbType.VarChar).Value = filtroorden;
                }
            }
            else
            {

                if (testpermiso == 4 || testperuser == 4)
                {
                    //comm.CommandText = select + " FROM  [ORDER] INNER JOIN COUNTY ON [ORDER].county = COUNTY.county_id INNER JOIN  STATE ON [ORDER].state = STATE.state_id AND COUNTY.state_id = STATE.state_id INNER JOIN STATUS ON [ORDER].status_id = STATUS.status_id INNER JOIN  PRODUCT ON [ORDER].product_id = PRODUCT.product_id WHERE UPPER(STATUS.name)<>'COMPLETED' ORDER BY 3 ASC, 4 DESC";
                    where = "";
                }
                else
                {
                    where = "  WHERE (UPPER(STATUS.name)<>'PAID' and UPPER(STATUS.name)<>'COMPLETED' ) ";
                }
                if (!filtroorden.Equals(""))
                {
                    where = where + " and ( [ORDER].ordernum like '%" + filtroorden + "%')";
                    comm.Parameters.Add("@ordernum", SqlDbType.VarChar).Value = filtroorden;
                }

            }


            if (testpermiso2 != 4 || testperuser2 != 4)
            {

                if (perfilID != 1)
                {
                    //where = where + " and ( Upper(ord_processor)='" + usinitial + "' OR  Upper(ord_driver)='" + usinitial + "'  OR Upper(ord_reprocessor)='" + usinitial + "' OR Upper(ord_redriver)='" + usinitial + "')";
                    where = where + " and ( case when ord_reprocessor is not null then Upper(ord_reprocessor) else Upper(ord_processor) end = '" + usinitial + "'  OR  case when ord_redriver is not null then Upper(ord_redriver) else Upper(ord_driver) end ='" + usinitial + "' )";

                }
                else if (testperuser2 != 4)
                {
                    where = where + " and ( case when ord_reprocessor is not null then Upper(ord_reprocessor) else Upper(ord_processor) end = '" + usinitial + "'  OR  case when ord_redriver is not null then Upper(ord_redriver) else Upper(ord_driver) end ='" + usinitial + "' )";
                }
            }

            if (perfilID != 1) { orderby = " ORDER BY due2 ASC, 4 ASC"; }
            else { orderby = " ORDER BY due2 DESC, 4 DESC"; }

            if (busqueda != 1)
            {
                if (!filterstatus.ToUpper().Equals("ALL") && !filterstatus.ToUpper().Equals("ALLPENDING"))
                {
                    where += pwhere;
                    where += pwhere2;
                    where += pwhere3;
                }
            }
            else
            {
                string where2 = "";
                if (pwhere.Length > 4)
                {
                    where = " WHERE " + pwhere.Substring(4, pwhere.Length - 4);

                    if (testpermiso2 != 4)
                    {
                        if (perfilID != 1)
                        {
                            //where = where + " and ( upper(orden.ord_processor)='" + usinitial.ToUpper() + "' OR  Upper(orden.ord_driver)='" + usinitial.ToUpper() + "' OR Upper(ord_reprocessor)='" + usinitial + "' OR Upper(ord_redriver)='" + usinitial + "' )";

                            where2 = " where ( case when ord_reprocessor is not null then Upper(ord_reprocessor) else Upper(ord_processor) end = '" + usinitial + "'  OR  case when ord_redriver is not null then Upper(ord_redriver) else Upper(ord_driver) end ='" + usinitial + "' )";
                        }
                        else if (testperuser2 != 4)
                        {
                            // where = where + " and ( upper(orden.ord_processor)='" + usinitial.ToUpper() + "' OR  Upper(orden.ord_driver)='" + usinitial.ToUpper() + "' OR Upper(ord_reprocessor)='" + usinitial + "' OR Upper(ord_redriver)='" + usinitial + "')";
                            where2 = " where ( case when ord_reprocessor is not null then Upper(ord_reprocessor) else Upper(ord_processor) end = '" + usinitial + "'  OR  case when ord_redriver is not null then Upper(ord_redriver) else Upper(ord_driver) end ='" + usinitial + "' )";
                        }
                    }
                }
                else
                {
                    where = "";
                    if (testpermiso2 != 4 || testperuser2 != 4)
                    {
                        if (perfilID != 1)
                        {
                            // where = where + " WHERE ( upper(orden.ord_processor)='" + usinitial.ToUpper() + "' OR  Upper(orden.ord_driver)='" + usinitial.ToUpper() + "' OR Upper(ord_reprocessor)='" + usinitial + "' OR Upper(ord_redriver)='" + usinitial + "')";
                            where2 = " WHERE ( case when ord_reprocessor is not null then Upper(ord_reprocessor) else Upper(ord_processor) end = '" + usinitial + "'  OR  case when ord_redriver is not null then Upper(ord_redriver) else Upper(ord_driver) end ='" + usinitial + "' )";
                        }
                        else if (testperuser2 != 4)
                        {
                            // where = where + " WHERE ( upper(orden.ord_processor)='" + usinitial.ToUpper() + "' OR  Upper(orden.ord_driver)='" + usinitial.ToUpper() + "' OR Upper(ord_reprocessor)='" + usinitial + "' OR Upper(ord_redriver)='" + usinitial + "' )";
                            where2 = " WHERE ( case when ord_reprocessor is not null then Upper(ord_reprocessor) else Upper(ord_processor) end = '" + usinitial + "'  OR  case when ord_redriver is not null then Upper(ord_redriver) else Upper(ord_driver) end ='" + usinitial + "' )";
                        }
                    }
                }

                selectDB = "Select * from ( " + selectDB + " , (CASE WHEN [ORDER].ord_failed is not null  THEN [ORDER].ord_resubomitted_done ELSE [ORDER].ord_submitted_done END) as ord_submit, [ORDER].ord_qc, [ORDER].ord_completeset, [ORDER].duedate as due2, case when ([ORDER].company =1 and [ORDER].paid<>'YES') then 0 else 1 end as PAID  ";

                from = from + "  " + where2 + " )AS orden ";

            }


            if (busqueda == 1)
            {
                HttpContext.Current.Session["wheredb"] = selectDB + from + where;
                HttpContext.Current.Session["selectdb"] = selectDB + from;

            }
            else
            {


                HttpContext.Current.Session["wheredb"] = selectDB + ", (CASE WHEN [ORDER].ord_failed is not null  THEN [ORDER].ord_resubomitted_done ELSE [ORDER].ord_submitted_done END) as ord_submit " + from + where;
                HttpContext.Current.Session["selectdb"] = selectDB + ", (CASE WHEN [ORDER].ord_failed is not null  THEN [ORDER].ord_resubomitted_done ELSE [ORDER].ord_submitted_done END) as ord_submit " + from;
            }

            if (filterstatus.Equals("unassigned") || filterstatus.Equals("unassignedphotos") || filterstatus.Equals("assigned") || filterstatus.Equals("ready") || filterstatus.Equals("processed") || filterstatus.Equals("processedphotos") || filterstatus.Equals("assignedphotos") || filterstatus.Equals("photos") || filterstatus.Equals("processedC"))
            {
                selectDB = "Select * from (" + selectDB + ", [ORDER].ord_reprocessor, [ORDER].ord_redriver, (CASE WHEN [ORDER].ord_failed is not null  THEN [ORDER].ord_resubomitted_done ELSE [ORDER].ord_submitted_done END) as ord_submit , [ORDER].duedate as due2, case when ([ORDER].company =1 and [ORDER].paid<>'YES') then 0 else 1 end as PAID ";
                from = from + " )AS orden ";
                HttpContext.Current.Session["wheredb"] = selectDB + from + where;
            }
            if (filterstatus.Equals("previus"))
            {
                string previus = (string)HttpContext.Current.Session["Previus"];
                if (previus != null)
                {
                    comm.CommandText = previus;
                    HttpContext.Current.Session["Previus"] = comm.CommandText;

                    string strprevius = previus.Replace(" ORDER BY orden.due2 ASC, 4 ASC", " ");
                    HttpContext.Current.Session["wheredb"] = strprevius;
                }
                else
                {
                    comm.CommandText = "";
                }
            }
            else
            {
                if (!selectDB.Contains("Select * from (")) { selectDB = selectDB + ",'','','' ,[ORDER].duedate as due2, case when ([ORDER].company =1 and [ORDER].paid<>'YES') then 0 else 1 end as PAID "; }
                comm.CommandText = selectDB + from + where + orderby;
                HttpContext.Current.Session["Previus"] = comm.CommandText;
            }


            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            int cont = 0;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //photos damages
                if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1); //orden#
                if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2);//due date
                if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3).ToString();//duetime
                if (!reader.IsDBNull(4)) rgb.strC5 = reader.GetString(4).ToString();//client
                if (!reader.IsDBNull(5)) rgb.strC6 = reader.GetInt32(5).ToString();//company
                if (!reader.IsDBNull(6)) rgb.strC7 = reader.GetInt32(6).ToString();//account
                if (!reader.IsDBNull(7)) rgb.strC8 = reader.GetString(7);//product name
                if (!reader.IsDBNull(8)) rgb.strC9 = reader.GetString(8);//st num
                if (!reader.IsDBNull(9)) rgb.strC10 = reader.GetString(9);//st address
                if (!reader.IsDBNull(10)) rgb.strC11 = reader.GetString(10);//city
                if (!reader.IsDBNull(11)) rgb.strC12 = reader.GetString(11);//state
                if (!reader.IsDBNull(12)) rgb.strC13 = reader.GetString(12);//county
                if (!reader.IsDBNull(13)) rgb.strC14 = reader.GetString(13);//zip
                if (!reader.IsDBNull(14)) rgb.strC15 = reader.GetString(14);//procesor initial
                if (!reader.IsDBNull(15)) rgb.strC16 = reader.GetString(15);//driver initial
                if (!reader.IsDBNull(16)) rgb.strC17 = reader.GetString(16);//qc initial
                if (!reader.IsDBNull(17)) rgb.strC18 = reader.GetString(17);//pi comments
                if (!reader.IsDBNull(18)) rgb.strC29 = reader.GetString(18);//POC Comments
                if (!reader.IsDBNull(19)) rgb.strC19 = reader.GetString(19);//status
                if (!reader.IsDBNull(20)) rgb.strC20 = reader.GetString(20);//appt date
                if (!reader.IsDBNull(21)) rgb.strC21 = reader.GetString(21);//appt time
                if (!reader.IsDBNull(22)) rgb.strC22 = reader.GetString(22);//appt comments
                if (!reader.IsDBNull(23)) rgb.strC30 = reader.GetString(23);//Drv. Comments
                if (!reader.IsDBNull(24)) rgb.strC23 = reader.GetString(24);//special attributes
                if (!reader.IsDBNull(25)) rgb.strC24 = reader.GetString(25);//ord_failed
                if (!reader.IsDBNull(26)) rgb.intC1 = reader.GetInt32(26);//ord_failed_id
                if (!reader.IsDBNull(27)) rgb.strC25 = reader.GetString(27); //ord_processor_done
                if (!reader.IsDBNull(28)) rgb.strC26 = reader.GetString(28); //ord_driver_done
                if (!reader.IsDBNull(29)) rgb.strC27 = reader.GetString(29); //ord_qc_done
                if (!reader.IsDBNull(30)) rgb.intC2 = reader.GetInt32(30); //orderid
                if (!reader.IsDBNull(31)) rgb.strC28 = reader.GetString(31); //ord_rv
                if (!reader.IsDBNull(37)) rgb.strC31 = reader.GetInt32(37).ToString(); //ord_paid

                object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC11, rgb.strC12, rgb.strC13, rgb.strC14, rgb.strC15, rgb.strC16, rgb.strC17, rgb.strC18, rgb.strC29, rgb.strC19, rgb.strC20, rgb.strC21, rgb.strC22, rgb.strC30, rgb.strC23, rgb.strC24, rgb.intC1, rgb.strC25, rgb.strC26, rgb.strC27, rgb.intC2, rgb.strC28, cont, rgb.strC31 };
                result.Tables["Tabla"].Rows.Add(objArr);
                cont++;
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace + e.Message);
            return null;
        }

        result.Tables.Add("TablaFail");
        result.Tables["TablaFail"].Columns.Add("order_fail_id");
        result.Tables["TablaFail"].Columns.Add("fail_id");
        result.Tables["TablaFail"].Columns.Add("agent");
        result.Tables["TablaFail"].Columns.Add("order_id");
        result.Tables["TablaFail"].Columns.Add("completed");

        SqlConnection connf = null;
        SqlCommand commf = null;
        SqlDataReader readerf = null;
        try
        {
            connf = OpenConnection();
            commf = new SqlCommand();
            commf.Connection = connf;
            commf.CommandType = CommandType.Text;
            string select = "SELECT   ORDER_FAIL.order_fail_id, ORDER_FAIL.fail_id, ORDER_FAIL.agent, ORDER_FAIL.order_id, ORDER_FAIL.completed   FROM  ORDER_FAIL INNER JOIN  [ORDER] ON ORDER_FAIL.order_id = [ORDER].order_id";
            commf.CommandText = select;
            readerf = commf.ExecuteReader();
            RE_GenericBean rgbf = null;
            while (readerf.Read())
            {
                rgbf = new RE_GenericBean();
                if (!readerf.IsDBNull(0)) rgbf.intC1 = readerf.GetInt32(0); //order_fail_id
                if (!readerf.IsDBNull(1)) rgbf.intC2 = readerf.GetInt32(1); //fail_id
                if (!readerf.IsDBNull(2)) rgbf.strC1 = readerf.GetString(2); //new agent
                if (!readerf.IsDBNull(3)) rgbf.intC3 = readerf.GetInt32(3); //order_id
                if (!readerf.IsDBNull(4)) rgbf.strC2 = readerf.GetString(4); // completed

                object[] objArrf = { rgbf.intC1, rgbf.intC2, rgbf.strC1, rgbf.intC3, rgbf.strC2 };
                result.Tables["TablaFail"].Rows.Add(objArrf);
            }
            connf.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            //return null;
        }
        return result;
    }

    public static DataSet GetOrdersAcc(long permisowk, long permisoDet, string usinitial, string pwhere, string pwhere2, string pwhere3, int busqueda, int perfilID)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Order #");//0
        result.Tables["Tabla"].Columns.Add("status");// 2status order
        result.Tables["Tabla"].Columns.Add("Client");//3
        result.Tables["Tabla"].Columns.Add("Company");//4
        result.Tables["Tabla"].Columns.Add("Account");//5
        result.Tables["Tabla"].Columns.Add("Type");//5
        result.Tables["Tabla"].Columns.Add("Street");//6
        result.Tables["Tabla"].Columns.Add("Street Address");//7
        result.Tables["Tabla"].Columns.Add("Zip");//8
        result.Tables["Tabla"].Columns.Add("orderid");//9 yes or no
        result.Tables["Tabla"].Columns.Add("fee");//10 ord_failed_id
        result.Tables["Tabla"].Columns.Add("psffee");//11 yes o no
        result.Tables["Tabla"].Columns.Add("Paid");// 1status order
        result.Tables["Tabla"].Columns.Add("PaidDate");// 1status order

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            string where = "";

            string orderby;
            string from;



            string selectDB = "";
            // if (pwhere != "") { pwhere += " and (Upper([ORDER].paid)<>'YES' OR  [ORDER].paid IS NULL) "; }
            where = pwhere;

            selectDB = "SELECT  [ORDER].ordernum, CONVERT(varchar,  STATUS.name) status, [ORDER].client_id, [ORDER].company,[ORDER].account , upper(PRODUCT.initial) product, upper([ORDER].stnum) stnum, upper([ORDER].stadd) stadd,  [ORDER].zip,    [ORDER].order_id,  cast([ORDER].fee as varchar(15)) as fee, cast( [ORDER].psfprice as varchar(15) ) as psfprice, case when [ORDER].paid = 'YES' then 'true' else 'false' end paid,  CONVERT(varchar, [ORDER].paid_date, 101) paiddate ";


            from = " FROM  [ORDER]  INNER JOIN STATUS ON [ORDER].status_id = STATUS.status_id INNER JOIN PRODUCT ON [ORDER].product_id = PRODUCT.product_id ";

            orderby = "ORDER BY 2 ASC ";


            comm.CommandText = selectDB + from + where + orderby;
            HttpContext.Current.Session["Previus"] = comm.CommandText;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {

                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //orden#
                if (!reader.IsDBNull(1)) rgb.strC3 = reader.GetString(1).ToString();//status name
                if (!reader.IsDBNull(2)) rgb.strC4 = reader.GetString(2);//client
                if (!reader.IsDBNull(3)) rgb.strC5 = reader.GetInt32(3).ToString();//company
                if (!reader.IsDBNull(4)) rgb.strC6 = reader.GetInt32(4).ToString();//account
                if (!reader.IsDBNull(5)) rgb.strC7 = reader.GetString(5);//product name
                if (!reader.IsDBNull(6)) rgb.strC8 = reader.GetString(6);//st num
                if (!reader.IsDBNull(7)) rgb.strC9 = reader.GetString(7);//st address
                if (!reader.IsDBNull(8)) rgb.strC10 = reader.GetString(8);//zip
                if (!reader.IsDBNull(9)) rgb.intC1 = reader.GetInt32(9);//company
                if (!reader.IsDBNull(10)) rgb.strC11 = reader.GetString(10).ToString(); //fee
                if (!reader.IsDBNull(11)) rgb.strC12 = reader.GetString(11);  //psfprice
                if (!reader.IsDBNull(12)) rgb.strC13 = reader.GetString(12);  //paid
                if (!reader.IsDBNull(13)) rgb.strC14 = reader.GetString(13);  //paid date

                if (rgb.strC4 == "PACIFICSTAR") { rgb.strC11 = rgb.strC12; }

                Utility.setVariablesSession();
                DataSet dscompany = (DataSet)HttpContext.Current.Session["companies"];
                DataSet dsaccounts = (DataSet)HttpContext.Current.Session["accounts"];
                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC5.ToString()))
                        {
                            rgb.strC5 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                if (dsaccounts != null)
                {
                    for (int ii = 0; ii <= (dsaccounts.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccounts.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC6.ToString()))
                        {
                            rgb.strC6 = dsaccounts.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                object[] objArr = { rgb.strC1, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.intC1, rgb.strC11, rgb.strC12, rgb.strC13, rgb.strC14 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace + e.Message);
            return null;
        }



        return result;
    }
    public static DataSet GetOrdersAccCli(long permisowk, long permisoDet, string usinitial, string pwhere, string pwhere2, string pwhere3, int busqueda, int perfilID)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Order #");//0
        result.Tables["Tabla"].Columns.Add("status");// 2status order
        result.Tables["Tabla"].Columns.Add("Client");//3
        result.Tables["Tabla"].Columns.Add("Company");//4
        result.Tables["Tabla"].Columns.Add("Account");//5
        result.Tables["Tabla"].Columns.Add("Type");//5
        result.Tables["Tabla"].Columns.Add("Street");//6
        result.Tables["Tabla"].Columns.Add("Street Address");//7
        result.Tables["Tabla"].Columns.Add("Zip");//8
        result.Tables["Tabla"].Columns.Add("orderid");//9 yes or no
        result.Tables["Tabla"].Columns.Add("fee");//10 ord_failed_id
        result.Tables["Tabla"].Columns.Add("psffee");//11 yes o no
        result.Tables["Tabla"].Columns.Add("Paid");// 1status order
        result.Tables["Tabla"].Columns.Add("PaidDate");// 1status order

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            string where = "";

            string orderby;
            string from;



            string selectDB = "";
            // if (pwhere != "") { pwhere += " and (Upper([ORDER].paid_client)<>'YES' OR  [ORDER].paid_client IS NULL) "; }
            where = pwhere;

            selectDB = "SELECT  [ORDER].ordernum, CONVERT(varchar,  STATUS.name) status, [ORDER].client_id, [ORDER].company,[ORDER].account , upper(PRODUCT.initial) product, upper([ORDER].stnum) stnum, upper([ORDER].stadd) stadd,  [ORDER].zip,    [ORDER].order_id,  cast([ORDER].fee as varchar(15)) as fee, cast( [ORDER].psfprice as varchar(15) ) as psfprice, case when [ORDER].paid = 'YES' then 'true' else 'false' end paid,  CONVERT(varchar, [ORDER].paid_client_date, 101) paiddate ";


            from = " FROM  [ORDER]  INNER JOIN STATUS ON [ORDER].status_id = STATUS.status_id INNER JOIN PRODUCT ON [ORDER].product_id = PRODUCT.product_id ";

            orderby = "ORDER BY 2 ASC ";


            comm.CommandText = selectDB + from + where + orderby;
            HttpContext.Current.Session["Previus"] = comm.CommandText;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {

                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //orden#
                if (!reader.IsDBNull(1)) rgb.strC3 = reader.GetString(1).ToString();//status name
                if (!reader.IsDBNull(2)) rgb.strC4 = reader.GetString(2);//client
                if (!reader.IsDBNull(3)) rgb.strC5 = reader.GetInt32(3).ToString();//company
                if (!reader.IsDBNull(4)) rgb.strC6 = reader.GetInt32(4).ToString();//account
                if (!reader.IsDBNull(5)) rgb.strC7 = reader.GetString(5);//product name
                if (!reader.IsDBNull(6)) rgb.strC8 = reader.GetString(6);//st num
                if (!reader.IsDBNull(7)) rgb.strC9 = reader.GetString(7);//st address
                if (!reader.IsDBNull(8)) rgb.strC10 = reader.GetString(8);//zip
                if (!reader.IsDBNull(9)) rgb.intC1 = reader.GetInt32(9);//company
                if (!reader.IsDBNull(10)) rgb.strC11 = reader.GetString(10).ToString(); //fee
                if (!reader.IsDBNull(11)) rgb.strC12 = reader.GetString(11);  //psfprice
                if (!reader.IsDBNull(12)) rgb.strC13 = reader.GetString(12);  //paid
                if (!reader.IsDBNull(13)) rgb.strC14 = reader.GetString(13);  //paid date

                Utility.setVariablesSession();
                DataSet dscompany = (DataSet)HttpContext.Current.Session["companies"];
                DataSet dsaccounts = (DataSet)HttpContext.Current.Session["accounts"];
                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC5.ToString()))
                        {
                            rgb.strC5 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                if (dsaccounts != null)
                {
                    for (int ii = 0; ii <= (dsaccounts.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccounts.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC6.ToString()))
                        {
                            rgb.strC6 = dsaccounts.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                object[] objArr = { rgb.strC1, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.intC1, rgb.strC11, rgb.strC12, rgb.strC13, rgb.strC14 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace + e.Message);
            return null;
        }



        return result;
    }

    public static DataSet GetOrdersPay(long permisowk, long permisoDet, string usinitial, string pwhere, string pwhere2, string pwhere3, int busqueda, int perfilID)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Order #");//0
        result.Tables["Tabla"].Columns.Add("status");// 2status order
        result.Tables["Tabla"].Columns.Add("Client");//3
        result.Tables["Tabla"].Columns.Add("Company");//4
        result.Tables["Tabla"].Columns.Add("Account");//5
        result.Tables["Tabla"].Columns.Add("Type");//5
        result.Tables["Tabla"].Columns.Add("Street");//6
        result.Tables["Tabla"].Columns.Add("Street Address");//7
        result.Tables["Tabla"].Columns.Add("Zip");//8
        result.Tables["Tabla"].Columns.Add("orderid");//9 yes or no
        result.Tables["Tabla"].Columns.Add("fee");//10 ord_failed_id
        result.Tables["Tabla"].Columns.Add("psffee");//11 yes o no
        result.Tables["Tabla"].Columns.Add("Paid");// 1status order
        result.Tables["Tabla"].Columns.Add("PaidDate");// 1status order

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            string where = "";

            string orderby;
            string from;



            string selectDB = "";

            if (pwhere != "") { pwhere += " and Upper([ORDER].paid)<>'YES'"; }
            where = pwhere;
            selectDB = "SELECT  [ORDER].ordernum, CONVERT(varchar,  STATUS.name) status, [ORDER].client_id, [ORDER].company,[ORDER].account , upper(PRODUCT.initial) product, upper([ORDER].stnum) stnum, upper([ORDER].stadd) stadd,  [ORDER].zip,    [ORDER].order_id,  cast([ORDER].fee as varchar(15)) as fee, cast( [ORDER].psfprice as varchar(15) ) as psfprice, case when [ORDER].paid = 'YES' then 'true' else 'false' end paid,  CONVERT(varchar, [ORDER].paid_date, 101) paiddate ";


            from = " FROM  [ORDER]  INNER JOIN STATUS ON [ORDER].status_id = STATUS.status_id INNER JOIN PRODUCT ON [ORDER].product_id = PRODUCT.product_id ";

            orderby = "ORDER BY 2 ASC ";


            comm.CommandText = selectDB + from + where + orderby;
            HttpContext.Current.Session["Previus"] = comm.CommandText;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {

                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //orden#
                if (!reader.IsDBNull(1)) rgb.strC3 = reader.GetString(1).ToString();//status name
                if (!reader.IsDBNull(2)) rgb.strC4 = reader.GetString(2);//client
                if (!reader.IsDBNull(3)) rgb.strC5 = reader.GetInt32(3).ToString();//company
                if (!reader.IsDBNull(4)) rgb.strC6 = reader.GetInt32(4).ToString();//account
                if (!reader.IsDBNull(5)) rgb.strC7 = reader.GetString(5);//product name
                if (!reader.IsDBNull(6)) rgb.strC8 = reader.GetString(6);//st num
                if (!reader.IsDBNull(7)) rgb.strC9 = reader.GetString(7);//st address
                if (!reader.IsDBNull(8)) rgb.strC10 = reader.GetString(8);//zip
                if (!reader.IsDBNull(9)) rgb.intC1 = reader.GetInt32(9);//company
                if (!reader.IsDBNull(10)) rgb.strC11 = reader.GetString(10).ToString(); //fee
                if (!reader.IsDBNull(11)) rgb.strC12 = reader.GetString(11);  //psfprice
                if (!reader.IsDBNull(12)) rgb.strC13 = reader.GetString(12);  //paid
                if (!reader.IsDBNull(13)) rgb.strC14 = reader.GetString(13);  //paid date

                Utility.setVariablesSession();
                DataSet dscompany = (DataSet)HttpContext.Current.Session["companies"];
                DataSet dsaccounts = (DataSet)HttpContext.Current.Session["accounts"];
                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC5.ToString()))
                        {
                            rgb.strC5 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                if (dsaccounts != null)
                {
                    for (int ii = 0; ii <= (dsaccounts.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccounts.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC6.ToString()))
                        {
                            rgb.strC6 = dsaccounts.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                object[] objArr = { rgb.strC1, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.intC1, rgb.strC11, rgb.strC12, rgb.strC13, rgb.strC14 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace + e.Message);
            return null;
        }



        return result;
    }

    public static DataSet GetProducts()
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Product_id");//1
        result.Tables["Tabla"].Columns.Add("Name");//2
        result.Tables["Tabla"].Columns.Add("Initial");//3
        result.Tables["Tabla"].Columns.Add("orden");//4
        result.Tables["Tabla"].Columns.Add("type");//5
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT  product_id, name, initial,orden, type from product where estado=1 order by orden asc";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //ordenid
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//due date
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//time
                if (!reader.IsDBNull(3)) rgb.intC2 = reader.GetInt32(3);//orden
                if (!reader.IsDBNull(4)) rgb.strC3 = reader.GetString(4);//orden

                object[] objArr = { rgb.intC1, rgb.strC1, rgb.strC2, rgb.intC4, rgb.strC3 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;

    }
    public static DataSet GetProductsbyUser(string usuid)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Product_id");//1
        result.Tables["Tabla"].Columns.Add("precio");//2

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection2();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT upr_prod_id, convert( varchar(10), upr_precio) FROM   tbl_usuario_precio WHERE  (upr_usu_id = @usuid)";
            comm.Parameters.Add("@usuid", SqlDbType.VarChar).Value = usuid;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //productid
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//due date


                object[] objArr = { rgb.intC1, rgb.strC1 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;

    }
    public static DataSet GetStates()
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("state_id");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("initial");//3
        result.Tables["Tabla"].Columns.Add("enable");//3


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT  state_id, Upper(name) AS name, initial, enable from state order by 2 asc";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //state_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//ma,e
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//initial
                if (!reader.IsDBNull(3)) rgb.intC2 = reader.GetInt32(3); //state_id
                object[] objArr = { rgb.intC1, rgb.strC1, rgb.strC2, rgb.intC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;

    }

    public static DataSet GetCounties(string state)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("county");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("enable");//3
        result.Tables["Tabla"].Columns.Add("initial");//4


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT c.county_id, c.name, c.enable, c.initial FROM COUNTY AS c INNER JOIN  STATE AS s ON c.state_id = s.state_id WHERE     (s.name = '" + state.ToString() + "') order by 2";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //county_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2); //enable
                if (!reader.IsDBNull(3)) rgb.strC2 = reader.GetString(3);//initial



                object[] objArr = { rgb.intC1, rgb.strC1, rgb.intC2, rgb.strC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;

    }
    public static DataSet GetCities(string county)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("citie");//1
        result.Tables["Tabla"].Columns.Add("name");//2



        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT c.city_id, c.name  FROM CITY AS c  WHERE    (county_id = '" + county.ToString() + "') order by 2";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //county_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name



                object[] objArr = { rgb.intC1, rgb.strC1 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;

    }

    public static int getProductId(string nameproduct)
    {//obttiene Product_id por el nombre del produto

        int result = 0;

        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select product_id from product where name = '" + nameproduct + "'";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "product");
            dt = ds.Tables["product"];
            if (dt.Rows.Count == 0)
            {
                result = 1;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila["product_id"].ToString());
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = -1;

        }
        return result;

    }
    public static int getProductIdbyInitial(string initialproduct)
    {

        int result = 0;

        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select product_id from product where initial = '" + initialproduct + "'";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "product");
            dt = ds.Tables["product"];
            if (dt.Rows.Count == 0)
            {
                result = 1;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila["product_id"].ToString());
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = -1;

        }
        return result;

    }

    public static int getCountyId(string namecounty, int stateid)
    {

        int result = 0;


        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select county_id from county where (UPPER(name) = '" + namecounty.ToUpper() + "') and state_id=" + stateid;
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "county");
            dt = ds.Tables["county"];
            if (dt.Rows.Count == 0)
            {
                result = 1;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila["county_id"].ToString());
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = -1;

        }
        return result;

    }

    public static int getStateId(string namestate)
    {

        int result = 0;


        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select state_id from state where (UPPER(name) = '" + namestate.ToUpper() + "')";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "state");
            dt = ds.Tables["state"];
            if (dt.Rows.Count == 0)
            {
                result = 1;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila["state_id"].ToString());
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = -1;

        }
        return result;

    }
    public static int isStateEnable(string state)
    {
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select enable from state where name = '" + state + "'";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "state");
            dt = ds.Tables["state"];
            if (dt.Rows.Count == 0)
            {
                result = 1;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila["state_id"].ToString());
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = -1;

        }
        return result;

    }
    public static int hasFail(int orderid)
    {
        int result = 0;


        try
        {

            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "SELECT COUNT(order_id)conteo FROM   ORDER_FAIL WHERE order_id = " + orderid;
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "tabla");
            dt = ds.Tables["tabla"];
            if (dt.Rows.Count == 0)
            {
                result = 0;
            }
            else
            {
                result = 1;
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError("DB has Fail" + e.StackTrace);

        }
        return result;


    }

    public static DataSet getFail(int orderid)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Fail");//1
        result.Tables["Tabla"].Columns.Add("Date");//2
        result.Tables["Tabla"].Columns.Add("Agent");//3
        result.Tables["Tabla"].Columns.Add("Submitted");//3
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT top (5) FAIL.description, convert(varchar(10),date,101), agent, submitted FROM   ORDER_FAIL INNER JOIN FAIL ON ORDER_FAIL.fail_id = FAIL.fail_id   WHERE order_id= " + orderid + " order by date desc";
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //fail
                if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//date
                if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2); //agent
                if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3); //responsable
                object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        conn.Close();
        return result;


    }

    public static DataSet getProcess(int product)
    {
        //devuelve los procesos de catalogo de un producto

        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("name");//Item
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT PROCESS.name FROM  PRODUCT INNER JOIN PRODUCTS_PROCESS ON PRODUCT.product_id = PRODUCTS_PROCESS.product_id INNER JOIN PROCESS ON PRODUCTS_PROCESS.process_id = PROCESS.process_id WHERE  (PRODUCT.product_id = " + product + ") AND (PROCESS.internal <> 1)";
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0);//
                object[] objArr = { rgb.strC1 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }


            conn.Close();


        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }


    public static DataSet getProcessProduct(int product)
    {//devuelve los procesos ya asignados a un producto, quien los puede realizar

        DataSet result = new DataSet();
        result.Tables.Add("Tabla");


        result.Tables["Tabla"].Columns.Add("PRODUCT");//product
        result.Tables["Tabla"].Columns.Add("VENDOR");//vendor
        result.Tables["Tabla"].Columns.Add("FEES");//
        result.Tables["Tabla"].Columns.Add("DONE");//
        result.Tables["Tabla"].Columns.Add("DATE");//Item

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT PROCESS.name, PROCESS.perfil, PROCESS.process_id FROM  PRODUCT INNER JOIN PRODUCTS_PROCESS ON PRODUCT.product_id = PRODUCTS_PROCESS.product_id INNER JOIN PROCESS ON PRODUCTS_PROCESS.process_id = PROCESS.process_id WHERE  (PRODUCT.product_id = " + product + ") order by PRODUCTS_PROCESS.orden";
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0);//name
                if (!reader.IsDBNull(1)) rgb.intC1 = reader.GetInt32(1);//perfil de quien puede hacer ese proceso
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2);//id del producto de process
                string srespuesta;

                //xml para obtener listado usuarios que pueden hacer esa acticidad
                // Service se= new Service();
                // srespuesta =   se.UsuariosporPerfil(int);
                //construyendo mi propia respuesta
                srespuesta = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
                srespuesta = srespuesta + "<lista_usuarios><respuestaID>1</respuestaID>";
                srespuesta = srespuesta + "<datos_registro><user></user><name></name><lastname></lastname><comp-name></comp-name><alias></alias><email></email></datos_registro>";
                srespuesta = srespuesta + "/lista_usuarios";

                object[] objArr = { rgb.strC1, rgb.intC1, rgb.intC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();




        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }

    public static int getPerfilProcess(string process)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT PROCESS.name, PROCESS.perfil FROM  PRODUCT INNER JOIN PRODUCTS_PROCESS ON PRODUCT.product_id = PRODUCTS_PROCESS.product_id INNER JOIN PROCESS ON PRODUCTS_PROCESS.process_id = PROCESS.process_id WHERE  (PRODUCT.product_id = " + process + ")";
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(0);//perfil
            }
            conn.Close();
        }
        catch (Exception e)
        {


        }

        return result;

    }

    public static RE_GenericBean getValueCampo(string campo, int order, string process)
    {
        RE_GenericBean rgb = null;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT TOP (1)  ORDER_PROCESS.value, ORDER_PROCESS.date  FROM  CAMPOS INNER JOIN PROCESS ON CAMPOS.process_id = PROCESS.process_id INNER JOIN ORDER_PROCESS ON CAMPOS.campo_id = ORDER_PROCESS.campo_id WHERE  (CAMPOS.name = '" + campo + "') AND (ORDER_PROCESS.order_id = " + order + ") AND (PROCESS.name = '" + process + "') ORDER BY ORDER_PROCESS.id DESC";
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0);//value
                if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//date
            }
            conn.Close();
        }
        catch (Exception e)
        {


        }


        return rgb;

    }

    public static int addFail(int orderid, int failid, string agent, string responsable)
    {
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = DB.OpenConnection();
            string now = DateTime.Now.ToString();
            string q = "insert into ORDER_FAIL (order_id, fail_id, date, agent, responsable) values (" + orderid + ", " + failid + " , getdate(),'" + agent + "', '" + responsable + "')";
            SqlCommand insert = new SqlCommand(q, conn);
            insert.ExecuteNonQuery();
            result = 1;
            conn.Close();
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace);
        }
        return result;

    }
    //DB.updateOrder(orden,p torder.p_2 Text,jobtype.Text,p_3cbstatus.Text, p_4company.Text, p_5account.Text,  p_8 tduedate.Text, p_9 tduetime.Text, p_10 tstnumber.Text, p_11 tstaddress.Text, p_12 tcity.Text, p_13 county.Text, p_14 state.Text, p_15 tzip.Text , p_16 comments.Text, attributes.text);
    public static int updateOrder(int orden, string p, int p_2, int p_3, string p_4, string p_5, string p_8, string p_9, string p_10, string p_11, string p_12, string p_13, string p_14, string p_15, string p_16, string attributes, string clientid, string fee, string psffee, RE_GenericBean rgapp, string paid, string psfpaid, string unit)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlTransaction transaccion;
        conn = DB.OpenConnection();
        transaccion = conn.BeginTransaction();

        try
        {


            string now = DateTime.Now.ToString();
            int stateid = getStateId(p_14);
            int county = getCountyId(p_13, stateid);
            //string q = "update [ORDER] set ordernum=" + p + ", product_id=" + p_2 + ", status_id=" + p_3 + ", company=" + p_4 + ", account=" + p_5 + ", duedate='" + p_8 + "', duetime='" + p_9 + "', stnum= '" + p_10 + "', stadd='" + p_11 + "', stcity= '" + p_12 + "', county=" + getCountyId(p_13, stateid) + ", state=" + stateid + ", zip='" + p_15 + "', comments='" + p_16 + "', specialatttributes='" + attributes + "' WHERE order_id=" + orden;
            string q = "update [ORDER] set ordernum=@p, product_id=@p_2 , status_id=@p_3 , company=@p_4 , account=@p_5, duedate=@p_8, duetime=@p_9, stnum= @p_10 , stadd=@p_11, stcity= @p_12 , county=@county, state=@stateid , zip=@p_15 , comments=@p_16, specialatttributes=@attributes, client_id=@client, fee=@fee, psfprice=@psffee, paid = @paid , unit= @unit WHERE order_id=@orden ";

            SqlCommand insert = new SqlCommand(q, conn);
            insert.Transaction = transaccion;
            insert.Parameters.Add("@p", SqlDbType.VarChar).Value = p;//torder
            insert.Parameters.Add("@p_2", SqlDbType.Int).Value = p_2;//product
            insert.Parameters.Add("@p_3", SqlDbType.Int).Value = p_3;//status
            insert.Parameters.Add("@p_4", SqlDbType.Int).Value = p_4;//company
            insert.Parameters.Add("@p_5", SqlDbType.Int).Value = p_5;//account
            // string[] fecha = p_8.Split('/');
            //insert.Parameters.Add("@p_8", SqlDbType.VarChar).Value = fecha[1]+"/"+fecha[0]+"/"+fecha[2];
            insert.Parameters.Add("@p_8", SqlDbType.VarChar).Value = p_8;
            insert.Parameters.Add("@p_9", SqlDbType.VarChar).Value = p_9;
            insert.Parameters.Add("@p_10", SqlDbType.VarChar).Value = p_10;
            insert.Parameters.Add("@p_11", SqlDbType.VarChar).Value = p_11;
            insert.Parameters.Add("@p_12", SqlDbType.VarChar).Value = p_12;
            insert.Parameters.Add("@county", SqlDbType.Int).Value = county;
            insert.Parameters.Add("@stateid", SqlDbType.Int).Value = stateid;
            insert.Parameters.Add("@p_15", SqlDbType.VarChar).Value = p_15;
            insert.Parameters.Add("@p_16", SqlDbType.VarChar).Value = p_16;
            insert.Parameters.Add("@attributes", SqlDbType.VarChar).Value = attributes;
            insert.Parameters.Add("@client", SqlDbType.VarChar).Value = clientid;
            insert.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            insert.Parameters.Add("@paid", SqlDbType.VarChar).Value = paid;
            insert.Parameters.Add("@unit", SqlDbType.VarChar).Value = unit;

            if (fee.Equals("")) { fee = "0.00"; }
            double auxfee = double.Parse(fee);
            if (auxfee >= 100 && auxfee < 10000) { auxfee = auxfee / 100; }
            insert.Parameters.Add("@fee", SqlDbType.Real).Value = auxfee;
            if (psffee.Equals("")) { psffee = "0.00"; }
            double auxpsffee = double.Parse(psffee);
            if (auxpsffee >= 100 && auxpsffee < 10000) { auxpsffee = auxpsffee / 100; }
            insert.Parameters.Add("@psffee", SqlDbType.Real).Value = auxpsffee;
            insert.ExecuteNonQuery();
            insert.Parameters.Clear();


            insert.CommandType = CommandType.Text;
            insert.CommandText = "update   [ORDER]  set contactinfo=@contactinfo, appcomments=@appcomments, ord_drvcomment= @drvcomments   where order_id=@idorder";
            insert.Parameters.Add("@idorder", SqlDbType.Int).Value = orden;
            insert.Parameters.Add("@contactinfo", SqlDbType.VarChar).Value = rgapp.strC1;
            insert.Parameters.Add("@appcomments", SqlDbType.VarChar).Value = rgapp.strC2;
            insert.Parameters.Add("@drvcomments", SqlDbType.VarChar).Value = rgapp.strC3;

            insert.ExecuteNonQuery();
            insert.Parameters.Clear();

            transaccion.Commit();
            conn.Close();

            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message + "/n /t " + e.Message);
            transaccion.Rollback();
        }
        return result;
    }

    public static int getStatusId(string p_3)
    {
        int result = 0;

        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select status_id from status where (UPPER(name) = '" + p_3.ToUpper() + "')";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "product");
            dt = ds.Tables["product"];
            conn.Close();
            if (dt.Rows.Count == 0)
            {
                result = 1;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila["status_id"].ToString());
                }
            }
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = -1;

        }
        return result;
    }
    // DB.updateOrderAttibutes(p attributes.Text, p_2 appshe.Text,p_3 tfee.Text,p_4 tcheck.Text, p_5 paid.Text, p_6 asisValue.Text, p_7 repair.Text, p_8 efectivedate.Text );
    public static int updateOrderAttibutes(int orden, string p, string p_2, string p_3, string p_4, string p_5, string p_6, string p_7, string p_8)
    {
        int result = 0;
        try
        {

            CultureInfo ci = new CultureInfo("en-US");
            if (p_8 == "")
            {
                p_8 = "";//validar que no se pueda registrar si no lleva esta fecha
            }


            SqlConnection conn = null;
            conn = DB.OpenConnection();
            if (p.ToUpper().Equals("YES")) { p = "YES"; } else { p = ""; }
            string q = "update [ORDER] set specialatttributes= '" + p + "', appscheduled='" + p_2 + "' , fee=" + p_3 + ", check# ='" + p_4 + "', paid='" + p_5 + "', asisvalue='" + p_6 + "', repairedvalue='" + p_7 + "',  efectivedate= '" + p_8 + "' WHERE order_id=" + orden;
            SqlCommand insert = new SqlCommand(q, conn);
            insert.ExecuteNonQuery();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace + e.Message);
        }
        return result;
    }

    public static int updateOrderFee(int orden, string p, string p_2)
    {
        int result = 0;
        try
        {

            SqlConnection conn = null;
            conn = DB.OpenConnection();
            string q = "update [ORDER] set fee=" + p + ", psfprice ='" + p_2 + "' WHERE order_id=" + orden;
            SqlCommand insert = new SqlCommand(q, conn);
            insert.ExecuteNonQuery();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace + e.Message);
        }
        return result;
    }

    // DB.saveOrderProcess(processname, campo, value);
    public static int saveOrderProcess(int order, int campoid, string value)
    {
        int result = 0;

        try
        {

            SqlConnection conn = null;
            SqlConnection conn2 = null;
            conn = OpenConnection();
            conn2 = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "SELECT TOP(1) ORDER_PROCESS.id, ORDER_PROCESS.order_id, ORDER_PROCESS.value   FROM   ORDER_PROCESS  WHERE    order_id = " + order + " AND  campo_id =" + campoid + " ORDER BY id DESC ";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "CAMPOS");
            dt = ds.Tables["CAMPOS"];
            if (dt.Rows.Count == 0) //save
            {

                string q = "insert into ORDER_PROCESS (order_id, campo_id, value, date) values (" + order + ", " + campoid + " , '" + value + "', getdate())";
                SqlCommand insert = new SqlCommand(q, conn2);
                insert.ExecuteNonQuery();
                result = 1;

            }
            else//update
            {
                int id = 0;
                string strvalue = "";
                foreach (DataRow fila in dt.Rows)
                {
                    id = int.Parse(fila[0].ToString());
                    strvalue = fila[2].ToString();
                }
                if (!strvalue.ToUpper().Equals(value.ToUpper()))
                {
                    string u = "update  ORDER_PROCESS  set  value='" + value + "', date='" + DateTime.Now.ToString() + "' WHERE id=" + id;
                    SqlCommand update = new SqlCommand(u, conn);
                    update.ExecuteNonQuery();
                    result = 1;
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = 0;

        }


        return result;

    }

    public static int getCampoID(string processname, string campo)
    {
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "SELECT CAMPOS.campo_id  FROM   CAMPOS INNER JOIN  PROCESS ON CAMPOS.process_id = PROCESS.process_id WHERE     (UPPER(PROCESS.name) = UPPER('" + processname + "')) AND (UPPER(CAMPOS.name) = UPPER('" + campo + "'))";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "CAMPOS");
            dt = ds.Tables["CAMPOS"];
            if (dt.Rows.Count == 0)
            {
                result = 1;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila["campo_id"].ToString());
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = -1;

        }


        return result;
    }

    public static DataSet getDoneProduct(int order, int intCampo)
    {
        DataSet ds = new DataSet();
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();

            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;


            string strsql = "SELECT ORDER_PROCESS.id, ORDER_PROCESS.order_id, ORDER_PROCESS.value   FROM   ORDER_PROCESS  WHERE    order_id = " + order + " AND  campo_id =" + intCampo;
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "CAMPOS");
            dt = ds.Tables["CAMPOS"];
            if (ds.Tables[0].Rows.Count == 0) { ds = null; }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
        }

        return ds;
    }

    public static int setStatusOrder(int order, int statusid)
    {
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            string strsql = "UPDATE [ORDER] set status_id=" + statusid + " WHERE    order_id = " + order;
            SqlCommand update = new SqlCommand(strsql, conn);
            update.ExecuteNonQuery();
            conn.Close();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
        }
        return result;

    }



    public static string getProductType(string productid)
    {
        string result = "none";
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "SELECT type  FROM   PRODUCT  WHERE     product_id = " + productid;
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "CAMPOS");
            dt = ds.Tables["CAMPOS"];

            if (dt.Rows.Count == 0)
            {
                result = "none";
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = fila[0].ToString();
                }

            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = "none";

        }



        return result;
    }
    /// <summary>
    /// esete
    /// </summary>
    /// <param name="product_id"></param>
    /// <returns></returns>
    public static DataSet getProductView(int product_id)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("name");
        result.Tables["Tabla"].Columns.Add("view_id");
        result.Tables["Tabla"].Columns.Add("num");
        result.Tables["Tabla"].Columns.Add("mandatory");


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT  [VIEW].name, [VIEW].view_id, PRODUCT_VIEW.num, PRODUCT_VIEW.mandatory FROM  PRODUCT_VIEW INNER JOIN  [VIEW] ON PRODUCT_VIEW.view_id = [VIEW].view_id WHERE        (PRODUCT_VIEW.product_id = " + product_id + ") ORDER BY  PRODUCT_VIEW.num";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0);//name
                if (!reader.IsDBNull(1)) rgb.intC2 = reader.GetInt32(1);//viewid
                if (!reader.IsDBNull(2)) rgb.intC3 = reader.GetInt32(2);//num
                if (!reader.IsDBNull(3)) rgb.intC4 = reader.GetInt32(3);//mandatory
                object[] objArr = { rgb.strC1, rgb.intC2, rgb.intC3, rgb.intC4 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        conn.Close();
        return result;

    }

    public static int nextPhoto()
    {
        int result = 0;


        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select top 1 photo_id from [PHOTO] order by 1 desc";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "order");
            dt = ds.Tables["order"];
            conn.Close();
            if (dt.Rows.Count == 0)
            {
                result = 1;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila[0].ToString()) + 1;
                }
            }
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = -1;

        }
        return result;
    }

    public static int addPhotorestriccion(int orden, int view, string comments, string path)
    {// inserta los datos de una foto a la BD
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = DB.OpenConnection();
            string now = DateTime.Now.ToString();
            int nextphoto = nextPhoto();
            if (nextphoto == 1)
            {
                nextphoto = 100;
            }

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select photo_id from PHOTO where view_id=" + view + " and order_id=" + orden;
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "photo");
            dt = ds.Tables["photo"];
            if (dt.Rows.Count == 0)
            {
                string q = "insert into PHOTO   (photo_id, view_id, order_id, comments, path) values (" + nextphoto + ", " + view + ", " + orden + " ,'" + comments + "', '" + path + "')";
                SqlCommand insert = new SqlCommand(q, conn);
                insert.ExecuteNonQuery();
                conn.Close();
                result = 1;
            }
            else
            {
                result = 0;
            }
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace);
        }
        return result;
    }

    public static int addPhoto(int orden, int view, string comments, string path)
    {// inserta los datos de una foto a la BD
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = DB.OpenConnection();
            string now = DateTime.Now.ToString();
            int nextphoto = nextPhoto();
            if (nextphoto == 1)
            {
                nextphoto = 100;
            }

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();


            string q = "insert into PHOTO   (photo_id, view_id, order_id, comments, path) values (" + nextphoto + ", " + view + ", " + orden + " ,'" + comments + "', '" + path + "')";
            SqlCommand insert = new SqlCommand(q, conn);
            insert.ExecuteNonQuery();
            conn.Close();
            result = nextphoto;

        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace);
        }
        return result;
    }
    public static int moveImage(string p)
    {
        int result = 0;
        try
        {

            string sourceFile = HttpContext.Current.Server.MapPath("~\\temp\\" + p);
            string destinationFile = HttpContext.Current.Server.MapPath("~\\data\\photos\\" + p);
            System.IO.File.Move(sourceFile, destinationFile);
            result = 1;
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write("<" + "script language='javascript'>");
            HttpContext.Current.Response.Write("alert('Image not Moved ." + p.ToString() + "');");
            HttpContext.Current.Response.Write("<" + "/script>");


        }
        return result;
    }

    public static string getStateInitial(string namestate)
    {

        string result = "";


        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "select initial from state where name = '" + namestate + "'";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "state");
            dt = ds.Tables["state"];
            if (dt.Rows.Count == 0)
            {
                result = "";
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = (fila[0].ToString());
                }
            }
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = "";

        }
        return result;

    }

    public static int getViewId(string nameView)
    {
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;

            string strsql = "SELECT view_id  FROM   [VIEW]  WHERE     (UPPER(name) = '" + nameView.ToUpper() + "')";
            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "CAMPOS");
            dt = ds.Tables["CAMPOS"];
            conn.Close();
            if (dt.Rows.Count == 0)
            {
                result = 0;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    result = int.Parse(fila[0].ToString());
                }
            }
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            result = 0;

        }



        return result;
    }



    public static DataSet getPhotosOrden(int orden)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("photo_id");
        result.Tables["Tabla"].Columns.Add("view_id");
        result.Tables["Tabla"].Columns.Add("num");
        result.Tables["Tabla"].Columns.Add("path");
        result.Tables["Tabla"].Columns.Add("comments");



        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT PHOTO.photo_id, PHOTO.view_id, PRODUCT_VIEW.num, PHOTO.path, PHOTO.comments FROM  PHOTO INNER JOIN [VIEW] ON PHOTO.view_id = [VIEW].view_id INNER JOIN PRODUCT_VIEW ON [VIEW].view_id = PRODUCT_VIEW.view_id INNER JOIN [ORDER] ON PHOTO.order_id = [ORDER].order_id INNER JOIN PRODUCT ON PRODUCT_VIEW.product_id = PRODUCT.product_id AND [ORDER].product_id = PRODUCT.product_id WHERE        ([ORDER].order_id = " + orden + ") ORDER BY PRODUCT_VIEW.num";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//photo_id
                if (!reader.IsDBNull(1)) rgb.intC2 = reader.GetInt32(1);//view_id
                if (!reader.IsDBNull(2)) rgb.intC3 = reader.GetInt32(2);//num
                if (!reader.IsDBNull(3)) rgb.strC2 = reader.GetString(3);//path
                if (!reader.IsDBNull(3)) rgb.strC3 = reader.GetString(4);//comments
                object[] objArr = { rgb.intC1, rgb.intC2, rgb.intC3, rgb.strC2, rgb.strC3 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }

    public static int savePhotosUploadby(int order, int campoid, string uploadby)
    {//Guarda la infomraicon de Updloadby de las photos 
        int result = 0;
        SqlDataReader reader = null;
        try
        {
            SqlConnection conn = null;
            conn = DB.OpenConnection();
            SqlConnection conninsert = DB.OpenConnection();
            string now = DateTime.Now.ToString();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();


            string verify = "select top (1) id, value from ORDER_PROCESS where order_id=" + order + " and campo_id=" + campoid + " order by id desc";
            SqlCommand select = new SqlCommand(verify, conn);
            reader = select.ExecuteReader();
            if (reader.HasRows)
            {
                string valor = "";
                while (reader.Read())
                {
                    if (!reader.IsDBNull(0))
                    {

                        valor = reader.GetString(1);//value

                        if (!valor.ToUpper().Equals(uploadby))
                        {

                            string q = "insert into [ORDER_PROCESS]   (order_id, campo_id,  value, date) values (" + order + ", " + campoid + ", '" + uploadby + "' , getdate() )";
                            SqlCommand insert = new SqlCommand(q, conninsert);
                            insert.ExecuteNonQuery();
                            result = 1;


                        }
                    }
                }
            }
            else
            {
                string qq = "insert into [ORDER_PROCESS]   (order_id, campo_id,  value, date) values (" + order + ", " + campoid + ", '" + uploadby + "' , getdate() )";
                SqlCommand insert2 = new SqlCommand(qq, conninsert);
                insert2.ExecuteNonQuery();
                conninsert.Close();
                result = 1;

            }


        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace);
        }


        return result;

    }

    public static int saveValueCampoComboBox(int orden, int campoid, string value)
    { //Guarda la informacion 
        int result = 0;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        SqlConnection conn2 = null;

        try
        {
            conn = null;
            conn = DB.OpenConnection();
            conn2 = DB.OpenConnection();
            string now = DateTime.Now.ToString();


            DataSet ds = new DataSet();
            DataTable dt = new DataTable();

            string date = DateTime.Now.ToString();
            string verify = "select id, value from ORDER_PROCESS where order_id=" + orden + " and campo_id=" + campoid;
            SqlCommand select = new SqlCommand(verify, conn);
            reader = select.ExecuteReader();

            if (reader.HasRows)
            {
                string valor = "";
                while (reader.Read())
                {
                    if (!reader.IsDBNull(1))
                    {

                        valor = reader.GetString(1);//value
                        if (!valor.ToUpper().Equals(value))
                        {
                            // string q = "uptade ORDER_PROCESS set value='" + value + "' where order_id=" + orden + " and campo_id=" + campoid;\
                            string q = "insert into [ORDER_PROCESS]   (order_id, campo_id,  value, date) values (" + orden + ", " + campoid + ", '" + value + "' , getdate() )";
                            SqlCommand insert = new SqlCommand(q, conn2);
                            insert.ExecuteNonQuery();
                            conn2.Close();
                            result = 1;
                        }
                    }
                }
            }
            else
            {
                string q = "insert into [ORDER_PROCESS]   (order_id, campo_id,  value, date) values (" + orden + ", " + campoid + ", '" + value + "' , getdate() )";
                SqlCommand insert = new SqlCommand(q, conn2);
                insert.ExecuteNonQuery();
                conn2.Close();
                result = 1;

            }

        }

        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace);
        }
        finally
        {
            conn.Close();
        }


        return result;

    }

    public static int saveValueCampo(int order, int campoid, string value)
    {//Guarda la infomraicon de Updloadby de las photos 
        int result = 0;
        SqlDataReader reader = null;
        SqlConnection conn2;
        try
        {
            SqlConnection conn = null;
            conn = DB.OpenConnection();
            conn2 = DB.OpenConnection();
            string now = DateTime.Now.ToString();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();


            string verify = "select top(1) id, value from ORDER_PROCESS where order_id=" + order + " and campo_id=" + campoid + "order by id DESC";
            SqlCommand select = new SqlCommand(verify, conn);
            reader = select.ExecuteReader();

            if (reader.HasRows)
            {

                string valor = "";
                while (reader.Read())
                {
                    if (!reader.IsDBNull(1))
                    {
                        valor = reader.GetString(1);//value
                        if (!valor.ToUpper().Equals(value))
                        {
                            string q = "insert into [ORDER_PROCESS]   (order_id, campo_id,  value, date) values (" + order + ", " + campoid + ", '" + value + "' , getdate() )";
                            SqlCommand insert = new SqlCommand(q, conn2);
                            insert.ExecuteNonQuery();
                            conn2.Close();
                            result = 1;
                        }
                    }

                }
            }
            else
            {
                if (!value.ToUpper().Equals(""))
                {
                    string q = "insert into [ORDER_PROCESS]   (order_id, campo_id,  value, date) values (" + order + ", " + campoid + ", '" + value + "' , getdate() )";
                    SqlCommand insert = new SqlCommand(q, conn2);
                    insert.ExecuteNonQuery();
                    conn2.Close();
                    result = 1;

                }

            }



        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace);
        }


        return result;
    }

    public static int getCountViewProduct(int productid)
    {
        //devuelve conteo de vistas por producto
        int result = 0;



        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select COUNT(v.view_id) from [VIEW] v, PRODUCT_VIEW pv, PRODUCT p where v.view_id=pv.view_id and pv.product_id=p.product_id and p.product_id=@productid and pv.mandatory=1 group by pv.product_id";
            comm.Parameters.Add("@productid", SqlDbType.VarChar).Value = productid;

            reader = comm.ExecuteReader();

            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetInt32(0);

            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return 0;
        }



        conn.Close();
        return result;

    }

    public static DataSet GetStatus()
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("status_id");//1
        result.Tables["Tabla"].Columns.Add("name");//2

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT status_id, name FROM status";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //status_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                object[] objArr = { rgb.intC1, rgb.strC1 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;

    }

    public static DataSet GetReasons()
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("fail_id");//1
        result.Tables["Tabla"].Columns.Add("description");//2


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT fail_id, UPPER(description) AS description FROM FAIL";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //fail_id
                if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//description
                object[] objArr = { rgb.intC1, rgb.strC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;

    }


    public static int addAppRecord(int orden, string outcome, string coordinator)
    {
        int result = 0;

        SqlConnection conn = null;
        SqlCommand comm = null;

        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "insert into   [APPDETAIL]  (idorder, outcome, date, responsable) values (@idorder, @outcome, getdate(), @responsable) ";
            comm.Parameters.Add("@idorder", SqlDbType.Int).Value = orden;
            comm.Parameters.Add("@outcome", SqlDbType.VarChar).Value = outcome;
            //comm.Parameters.Add("@date", SqlDbType.VarChar).Value = DateTime.Now.ToString();
            comm.Parameters.Add("@responsable", SqlDbType.VarChar).Value = coordinator;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
            result = 1;

        }
        catch (Exception e)
        {
            Utility.writeError("No se pudo agregar a APPDetail orden: " + orden + " " + e.Message);
            result = 0;
        }



        conn.Close();
        return result;
    }

    public static DataSet getAppDetail(int orden, int tam)
    {
        //devuelve conteo de vistas por producto si tipo=0 solo muestra 5 reg, si tipo=1 muestra todos
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Outcome");//1
        result.Tables["Tabla"].Columns.Add("Date");//2
        result.Tables["Tabla"].Columns.Add("Time");//3
        result.Tables["Tabla"].Columns.Add("Coordinator");//3

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (tam == -1)
            {
                comm.CommandText = "select   outcome, date, date, responsable from [APPDETAIL] where idorder=@orden order by  idappdetail DESC";
            }
            else
            {
                comm.CommandText = "select top (" + tam + ") outcome, date, date, responsable from [APPDETAIL] where idorder=@orden order by  idappdetail DESC";
            }
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //outcome
                if (!reader.IsDBNull(1)) rgb.strC2 = Utility.getsrtDate(reader.GetString(1));//date
                if (!reader.IsDBNull(2)) rgb.strC3 = Utility.getsrtTime(reader.GetString(2));//date
                if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3);//responsable
                object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();


        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);

        }



        conn.Close();
        return result;


    }

    public static RE_GenericBean updateAppoitment(string outcome, string coordinator, int orderid, string dateapp, int appt, string apptime, string newduedate, int sumarfecha)
    {//agrega los campos de appdate y appcoordinator a la tabla de ordenes de una orden en especifico
        RE_GenericBean result = new RE_GenericBean();

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlTransaction tran;
        conn = OpenConnection();
        tran = conn.BeginTransaction();


        try
        {


            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.Transaction = tran;
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "insert into   [APPDETAIL]  (idorder, outcome, date, responsable) values (@idorder, @outcome, getdate(), @responsable) ";
            comm.Parameters.Add("@idorder", SqlDbType.Int).Value = orderid;
            comm.Parameters.Add("@outcome", SqlDbType.VarChar).Value = outcome;
            //comm.Parameters.Add("@date", SqlDbType.VarChar).Value = DateTime.Now.ToString();
            comm.Parameters.Add("@responsable", SqlDbType.VarChar).Value = coordinator;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();


            comm.CommandText = "UPDATE    [ORDER] SET  appdate = @appdate , appcoordinator = @coordinator, appoutcome = @outcome, appt = @appt, apptime=@apptime WHERE   (order_id = @idorder)";
            comm.Parameters.Add("@idorder", SqlDbType.Int).Value = orderid;
            comm.Parameters.Add("@appdate", SqlDbType.VarChar).Value = dateapp;
            comm.Parameters.Add("@coordinator", SqlDbType.VarChar).Value = coordinator;
            comm.Parameters.Add("@outcome", SqlDbType.VarChar).Value = outcome;
            comm.Parameters.Add("@appt", SqlDbType.Int).Value = appt;
            comm.Parameters.Add("@apptime", SqlDbType.VarChar).Value = apptime;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();

            if (sumarfecha == 1)
            {
                comm.CommandText = "update  [ORDER] set duedate= DATEADD(day, 1, @duedate) where order_id=@id";
            }
            else
            {
                comm.CommandText = "update  [ORDER] set duedate=@duedate where order_id=@id";
            }

            comm.Parameters.Add("@id", SqlDbType.Int).Value = orderid;

            comm.Parameters.Add("@duedate", SqlDbType.VarChar).Value = newduedate;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
            tran.Commit();

            comm.CommandText = "select CONVERT(varchar,[ORDER].duedate,101) from [ORDER] where order_id=@id";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = orderid;
            SqlDataReader reader = comm.ExecuteReader();
            while (reader.Read())
            {
                // if (!reader.IsDBNull(0)) result.strC1 = Utility.getsrtDate(reader.GetString(0));//date
                if (!reader.IsDBNull(0)) result.strC1 = reader.GetString(0);//date


            }





            result.intC1 = 1;


        }
        catch (Exception e)
        {
            Utility.writeError("No se pudo agregar a addAppointment orden: " + orderid + " " + e.Message);
            tran.Rollback();
            result.intC1 = 0;
        }



        conn.Close();
        return result;
    }

    public static int updateAppInfo(string contactapp, string appcomments, int orderid)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;

        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "update   [ORDER]  set contactinfo=@contactinfo, appcomments=@appcomments   where order_id=@idorder";
            comm.Parameters.Add("@idorder", SqlDbType.Int).Value = orderid;
            comm.Parameters.Add("@contactinfo", SqlDbType.VarChar).Value = contactapp;
            comm.Parameters.Add("@appcomments", SqlDbType.VarChar).Value = appcomments;

            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
            result = 1;

        }
        catch (Exception e)
        {
            Utility.writeError("No se pudo agregar a addAppointment orden: " + orderid + " " + e.Message);
            result = 0;
        }



        conn.Close();

        return result;
    }

    public static int setAPPT(int id_order, int val)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "update  [ORDER] set appt=@appt where order_id=@id";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = id_order;
            comm.Parameters.Add("@appt", SqlDbType.Int).Value = val;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }
        finally
        {
            conn.Close();
        }

        return result;
    }

    public static int updatePhotoID(int photoid, int viewid, string comment, string path)
    {//actualiza cada foto
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "update  [PHOTO] set view_id=@viewid, comments=@comments, path=@path where photo_id=@id";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = photoid;
            comm.Parameters.Add("@viewid", SqlDbType.Int).Value = viewid;
            comm.Parameters.Add("@comments", SqlDbType.VarChar).Value = comment;
            comm.Parameters.Add("@path", SqlDbType.VarChar).Value = path;
            comm.ExecuteNonQuery();

            comm.Parameters.Clear();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }
        finally
        {
            conn.Close();
        }

        return result;

    }

    public static int updateCommentsPhoto(int order, string comment)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "update  [ORDER] set appcomments=@appcomm where order_id=@id";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = order;
            comm.Parameters.Add("@appcomm", SqlDbType.VarChar).Value = comment;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }
        finally
        {
            conn.Close();
        }
        return result;
    }

    public static int updateDueDate(string duedate, int orden)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;

        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "update  [ORDER] set duedate=@duedate where order_id=@id";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = orden;
            comm.Parameters.Add("@duedate", SqlDbType.Date).Value = duedate;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }
        finally
        {
            conn.Close();
        }
        return result;
    }

    public static int SaveProcess(string campotbl, string vendorvalue, int orden)
    {//guarda en el campo campotbl el valor vendorvalue de la orden orden. actualizaq si ya esta o guarda
        int result = 0;
        SqlConnection conn = null;
        SqlCommand commupdate = null;

        try
        {

            commupdate = new SqlCommand();
            conn = OpenConnection();
            commupdate.Connection = conn;
            commupdate.CommandType = CommandType.Text;
            commupdate.CommandText = "update [ORDER] set " + campotbl + "= @value where order_id=@orden";
            commupdate.Parameters.Add("@orden", SqlDbType.Int).Value = orden;

            commupdate.Parameters.Add("@value", SqlDbType.VarChar).Value = vendorvalue;
            commupdate.ExecuteNonQuery();
            result = 1;

            conn.Close();



            commupdate.Parameters.Clear();


            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }

        return result;
    }

    public static string getValueProcess(string campotbl, int orden)
    {
        //devuelve valor string de un ampo determinado de una orden determinada
        string result = "";

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select " + campotbl + " from [ORDER] where order_id=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetString(0); //CAMPOTABLA
            }
            conn.Close();


        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);

        }
        return result;

    }

    public static string getValueCampoTabla(string campotbl, string tabla, string criterio, int orden, int strint)
    {
        //devuelve valor string de un ampo determinado de una orden determinada, si es string=0 si ese entero =1, si es double =2
        string result = "";

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select " + campotbl + " from [" + tabla + "] where " + criterio + "=@orden ";
            //si es un campo float real
            if (strint == 2)
            {
                comm.CommandText = "select CAST( (case WHEN " + campotbl + "  IS NULL THEN -1 ELSE " + campotbl + " END) as varchar )from [" + tabla + "] where " + criterio + "=@orden ";
            }
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            if (strint == 0)
            {
                while (reader.Read())
                {
                    if (!reader.IsDBNull(0)) result = reader.GetString(0); //CAMPOTABLA
                }
            }
            else if (strint == 1)
            {
                int aux = 0;
                while (reader.Read())
                {
                    if (!reader.IsDBNull(0)) aux = reader.GetInt32(0); //CAMPOTABLA
                }
                result = Convert.ToString(aux);
            }
            else if (strint == 2)
            {
                string aux = "-1";
                while (reader.Read())
                {

                    if (!reader.IsDBNull(0)) aux = reader.GetString(0); //CAMPOTABLA double
                }
                Utility.writeError("antes de convervir aux float tiene " + aux);
                result = Convert.ToString(aux);
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            result = "-1";
        }
        return result;

    }


    public static int getValueIntProcess(string campotbl, int orden)
    {
        //devuelve valor string de un ampo determinado de una orden determinada
        int result = 0;

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select " + campotbl + " from [ORDER] where order_id=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetInt32(0); //CAMPOTABLA
            }
            conn.Close();


        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);

        }
        return result;

    }

    public static string getValueProcessDate(string campotbl, int orden)
    {
        //devuelve valor string de un ampo determinado de una orden determinada
        string result = "";

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select convert(varchar(10)," + campotbl + ",101) from [ORDER] where order_id=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetString(0); //CAMPOTABLA
            }
            conn.Close();


        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);

        }


        conn.Close();
        return result;


    }


    public static string getValueProcessTime(string campotbl, int orden)
    {
        //devuelve valor string de un ampo determinado de una orden determinada
        string result = "";

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select convert(varchar(5)," + campotbl + ",114) from [ORDER] where order_id=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetString(0); //CAMPOTABLA
            }
            conn.Close();


        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);

        }


        conn.Close();
        return result;


    }

    public static int SaveProcessDateyTime(string campotbldate, string campotbltime, string vendorvalue, string hora, int orden)
    {//guarda en el campo campotbl el valor vendorvalue de la orden orden. actualizaq si ya esta o guarda
        int result = 0;
        SqlConnection conn = null;
        SqlCommand commupdate = null;
        // Utility.writeError("hORA ANTES GUARDAR PROCESO "+hora);
        try
        {
            commupdate = new SqlCommand();
            conn = OpenConnection();
            commupdate.Connection = conn;
            commupdate.CommandType = CommandType.Text;
            commupdate.CommandText = "update [ORDER] set " + campotbldate + "= getdate(), " + campotbltime + "= @time where order_id=@orden";
            commupdate.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            //commupdate.Parameters.Add("@date", SqlDbType.VarChar).Value = vendorvalue;
            commupdate.Parameters.Add("@time", SqlDbType.VarChar).Value = hora;
            commupdate.ExecuteNonQuery();
            result = 1;
            Utility.writeError("guardo en " + campotbltime + " exitosamente " + hora);
            conn.Close();
            commupdate.Parameters.Clear();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError("NO guardo fecha y hora en saveprocessdatetime FEcg " + campotbldate + " " + orden.ToString() + "*********" + e.Message + e.StackTrace);
        }
        return result;
    }

    public static int SaveProcessDateyTime2(string campotbldate, string campotbltime, string vendorvalue, string hora, int orden)
    {//guarda en el campo campotbl el valor vendorvalue de la orden orden. actualizaq si ya esta o guarda
        int result = 0;
        SqlConnection conn = null;
        SqlCommand commupdate = null;
        // Utility.writeError("hORA ANTES GUARDAR PROCESO "+hora);
        try
        {
            commupdate = new SqlCommand();
            conn = OpenConnection();
            commupdate.Connection = conn;
            commupdate.CommandType = CommandType.Text;
            commupdate.CommandText = "update [ORDER] set " + campotbldate + "= @date, " + campotbltime + "= @time  where order_id=@orden";
            commupdate.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            commupdate.Parameters.Add("@date", SqlDbType.VarChar).Value = vendorvalue;
            commupdate.Parameters.Add("@time", SqlDbType.VarChar).Value = hora;
            commupdate.ExecuteNonQuery();
            result = 1;
            Utility.writeError("guardo en " + campotbltime + " exitosamente " + hora);
            conn.Close();
            commupdate.Parameters.Clear();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError("NO guardo fecha y hora en saveprocessdatetime FEcg " + campotbldate + " " + orden.ToString() + "*********" + e.Message + e.StackTrace);
        }
        return result;
    }

    public static int getCountFail(int orden)
    {
        //devuelve conteo de vistas por producto
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select COUNT(f.order_id) from [ORDER_FAIL] f, [ORDER] o  where f.order_id=o.order_id and o.order_id=@orderid ";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;

            reader = comm.ExecuteReader();

            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetInt32(0);

            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return 0;
        }



        conn.Close();
        return result;

    }

    public static int getStatusOrder(int orden)
    {
        //devuelve valor del status_id de una orden determinada
        int result = 0;

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select status_id from [ORDER] where order_id=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetInt32(0); //CAMPOTABLA
            }
            conn.Close();


        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);

        }
        return result;

    }

    public static int addFail(int orden, int failid, string agent, string responsable, string newqc, string newsubb, string commentsfail, string newcompleted, string time, string date)
    {
        int result = 0;
        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        conn = OpenConnection();
        transaction = conn.BeginTransaction();

        try
        {
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.Transaction = transaction;
            comm.CommandText = "insert into ORDER_FAIL (order_id, fail_id, date, agent, responsable, qc, submitted, comments, time, completed) values (@orderid,@failid, GETDATE(), @agent, @responsable, @qc, @submitted,@comments, @time, @completed )";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;
            comm.Parameters.Add("@failid", SqlDbType.Int).Value = failid;
            comm.Parameters.Add("@time", SqlDbType.VarChar).Value = time;
            comm.Parameters.Add("@agent", SqlDbType.VarChar).Value = agent;
            comm.Parameters.Add("@responsable", SqlDbType.VarChar).Value = responsable;
            comm.Parameters.Add("@qc", SqlDbType.VarChar).Value = newqc;
            comm.Parameters.Add("@submitted", SqlDbType.VarChar).Value = newsubb;
            comm.Parameters.Add("@comments", SqlDbType.VarChar).Value = commentsfail;
            comm.Parameters.Add("@completed", SqlDbType.VarChar).Value = newcompleted;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();


            comm.CommandText = "update [ORDER] set ord_failed= 'YES' where order_id = @orderid";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();

            result = 1;
            transaction.Commit();
        }
        catch (Exception e)
        {
            transaction.Rollback();

            return 0;
        }
        finally
        {

            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }

    public static int SaveProcessInt(string campotbl, int valor, int orden)
    {
        //guarda en el campo campotbl el valor vendorvalue de la orden orden. actualizaq si ya esta o guarda
        int result = 0;
        SqlConnection conn = null;
        SqlCommand commupdate = null;

        try
        {

            commupdate = new SqlCommand();
            conn = OpenConnection();
            commupdate.Connection = conn;
            commupdate.CommandType = CommandType.Text;
            commupdate.CommandText = "update [ORDER] set " + campotbl + "= @value where order_id=@orden";
            commupdate.Parameters.Add("@orden", SqlDbType.Int).Value = orden;

            commupdate.Parameters.Add("@value", SqlDbType.VarChar).Value = valor;
            commupdate.ExecuteNonQuery();
            result = 1;

            conn.Close();



            commupdate.Parameters.Clear();


            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }

        return result;
    }

    public static DataSet getOrderFail(int order_id)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("order_fail_id");
        result.Tables["Tabla"].Columns.Add("fail_id");
        result.Tables["Tabla"].Columns.Add("date");
        result.Tables["Tabla"].Columns.Add("agent");
        result.Tables["Tabla"].Columns.Add("responsable");
        result.Tables["Tabla"].Columns.Add("qc");
        result.Tables["Tabla"].Columns.Add("submitted");
        result.Tables["Tabla"].Columns.Add("comments");
        result.Tables["Tabla"].Columns.Add("time");
        result.Tables["Tabla"].Columns.Add("ord_id");
        result.Tables["Tabla"].Columns.Add("completed");
        result.Tables["Tabla"].Columns.Add("completed_date");
        result.Tables["Tabla"].Columns.Add("completed_time");
        result.Tables["Tabla"].Columns.Add("qc_date");
        result.Tables["Tabla"].Columns.Add("qc_time");
        result.Tables["Tabla"].Columns.Add("submitted_date");
        result.Tables["Tabla"].Columns.Add("submitted_time");
        result.Tables["Tabla"].Columns.Add("description");
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT  ORDER_FAIL.order_fail_id, ORDER_FAIL.fail_id, convert(varchar(10),ORDER_FAIL.date,101), ORDER_FAIL.agent, ORDER_FAIL.responsable, ORDER_FAIL.qc, ORDER_FAIL.submitted, ORDER_FAIL.comments, convert(varchar(5),ORDER_FAIL.time,114), ORDER_FAIL.order_id, ORDER_FAIL.completed , convert(varchar(10),ORDER_FAIL.completed_date,101), convert(varchar(5),ORDER_FAIL.completed_time,114),convert(varchar(10),ORDER_FAIL.qc_date,101), convert(varchar(5),ORDER_FAIL.qc_time,114), convert(varchar(10),ORDER_FAIL.submitted_date,101), convert(varchar(5),ORDER_FAIL.submitted_time,114), [FAIL].description  FROM  ORDER_FAIL, FAIL  WHERE  (ORDER_FAIL.order_id = " + order_id + ") and [ORDER_FAIL].fail_id = [FAIL].fail_id ORDER BY ORDER_FAIL.order_fail_id desc";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//order_fail_id
                if (!reader.IsDBNull(1)) rgb.intC2 = reader.GetInt32(1);//fail_id
                if (!reader.IsDBNull(2)) rgb.strC1 = reader.GetString(2);//date
                if (!reader.IsDBNull(3)) rgb.strC2 = reader.GetString(3);//agent
                if (!reader.IsDBNull(4)) rgb.strC3 = reader.GetString(4);//responsable
                if (!reader.IsDBNull(5)) rgb.strC4 = reader.GetString(5);//qc
                if (!reader.IsDBNull(6)) rgb.strC5 = reader.GetString(6);//submitted
                if (!reader.IsDBNull(7)) rgb.strC6 = reader.GetString(7);//comments
                if (!reader.IsDBNull(8)) rgb.strC7 = reader.GetString(8);//time
                if (!reader.IsDBNull(9)) rgb.intC3 = reader.GetInt32(9);//ord_id
                if (!reader.IsDBNull(10)) rgb.strC8 = reader.GetString(10);//completed
                if (!reader.IsDBNull(11)) rgb.strC9 = reader.GetString(11);//completed_date
                if (!reader.IsDBNull(12)) rgb.strC10 = reader.GetString(12);//completed_time
                if (!reader.IsDBNull(13)) rgb.strC11 = reader.GetString(13);//qc_date
                if (!reader.IsDBNull(14)) rgb.strC12 = reader.GetString(14);//qc_time
                if (!reader.IsDBNull(15)) rgb.strC13 = reader.GetString(15);//submitted_date
                if (!reader.IsDBNull(16)) rgb.strC14 = reader.GetString(16);//submitted_time
                if (!reader.IsDBNull(17)) rgb.strC15 = reader.GetString(17);//submitted_time
                object[] objArr = { rgb.intC1, rgb.intC2, rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.intC3, rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC11, rgb.strC12, rgb.strC13, rgb.strC14, rgb.strC15 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        conn.Close();
        return result;
    }

    public static int getLastFailbyOrder(int orden)
    {
        int result = 0;


        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select top 1 order_fail_id from [ORDER_FAIL] where order_id=@orderid order by 1 desc";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetInt32(0); // order_fail_id
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.Message);
            result = 0;

        }
        return result;
    }

    public static int updateFail(int order_fail_id, int orden, string agent, string qc, string submitted, string commentsfail, string completed)
    {
        //guarda en el campo campotbl el valor vendorvalue de la orden orden. actualizaq si ya esta o guarda
        int result = 0;
        SqlConnection conn = null;
        SqlCommand commupdate = null;

        try
        {

            commupdate = new SqlCommand();
            conn = OpenConnection();
            commupdate.Connection = conn;
            commupdate.CommandType = CommandType.Text;
            commupdate.CommandText = "update [ORDER_FAIL] set qc= @qc, agent=@agent, submitted=@submitted, comments=@comments, completed=@completed where order_id=@orden and order_fail_id=@orderfailid";
            commupdate.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            commupdate.Parameters.Add("@orderfailid", SqlDbType.Int).Value = order_fail_id;
            commupdate.Parameters.Add("@qc", SqlDbType.VarChar).Value = qc;
            commupdate.Parameters.Add("@agent", SqlDbType.VarChar).Value = agent;
            commupdate.Parameters.Add("@completed", SqlDbType.VarChar).Value = completed;
            commupdate.Parameters.Add("@submitted", SqlDbType.VarChar).Value = submitted;
            commupdate.Parameters.Add("@comments", SqlDbType.VarChar).Value = commentsfail;
            commupdate.ExecuteNonQuery();
            result = 1;

            conn.Close();



            commupdate.Parameters.Clear();


            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }

        return result;
    }
    public static int saveValueCampoTabla(string campotbl, string tabla, string valor, string criterio, int valorcriterio, int tipo)
    {
        //devuelve valor string de un ampo determinado de una orden determinada, tipo=0 es string,  tipo=1 es int, tipo=2 date, tipo=3 fecha
        int result = 0;

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "update [" + tabla + "] set " + campotbl + "= @valor where " + criterio + "=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = valorcriterio;
            if (tipo == 0)
            {
                comm.Parameters.Add("@valor", SqlDbType.VarChar).Value = valor;
            }
            if (tipo == 1)
            {
                comm.Parameters.Add("@valor", SqlDbType.Int).Value = valor;
            }
            if (tipo == 2)
            {
                comm.Parameters.Add("@valor", SqlDbType.VarChar).Value = valor;
            }
            if (tipo == 3)
            {
                comm.Parameters.Add("@valor", SqlDbType.VarChar).Value = valor;
            }

            comm.ExecuteNonQuery();
            result = 1;
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            result = 0;

        }
        return result;

    }


    public static int setDataPhotos(string complete, string exterioronly, string photosreceive, string uploadby, int orden)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;

        try
        {

            comm = new SqlCommand();
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "update [ORDER] set  ord_receivephotos=@rc, ord_completeset=@complete, ord_exterioronly=@ext, ord_uploadby=@uploadby, ord_upload_date= getdate(), ord_upload_time=@time where order_id=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            comm.Parameters.Add("@rc", SqlDbType.VarChar).Value = photosreceive;
            comm.Parameters.Add("@complete", SqlDbType.VarChar).Value = complete;
            comm.Parameters.Add("@ext", SqlDbType.VarChar).Value = exterioronly;
            comm.Parameters.Add("@uploadby", SqlDbType.VarChar).Value = uploadby;
            //comm.Parameters.Add("@date", SqlDbType.Date).Value = DateTime.Today.ToShortDateString();
            comm.Parameters.Add("@time", SqlDbType.VarChar).Value = Utility.convertTime();
            comm.ExecuteNonQuery();
            result = 1;

            conn.Close();



            comm.Parameters.Clear();


            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }


        return result;
    }

    public static int setDataCompletePhotos(string complete, string responsable, int orden, string done)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;

        try
        {

            comm = new SqlCommand();
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "update [ORDER] set ord_completeset=@complete,  ord_uploadby=@uploadby, ord_upload_date= getdate(), ord_upload_time=@time,  ord_driver_done=@done where order_id=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            comm.Parameters.Add("@complete", SqlDbType.VarChar).Value = complete;
            comm.Parameters.Add("@uploadby", SqlDbType.VarChar).Value = responsable;
            comm.Parameters.Add("@time", SqlDbType.VarChar).Value = Utility.convertTime();
            comm.Parameters.Add("@done", SqlDbType.VarChar).Value = done;
            comm.ExecuteNonQuery();
            result = 1;

            conn.Close();



            comm.Parameters.Clear();


            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError("Error no guardo completedset " + e.Message + e.StackTrace);
        }


        return result;
    }


    public static DataSet getUploadPhotos(int order_id)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("ord_receivephotos");//1
        result.Tables["Tabla"].Columns.Add("ord_completeset");//2
        result.Tables["Tabla"].Columns.Add("ord_exterioronly");//3
        result.Tables["Tabla"].Columns.Add("ord_uploadby");//4
        result.Tables["Tabla"].Columns.Add("ord_upload_date");//5
        result.Tables["Tabla"].Columns.Add("ord_upload_time");//6


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT [ORDER].ord_receivephotos, [ORDER].ord_completeset, [ORDER].ord_exterioronly, [ORDER].ord_uploadby, convert(varchar(10),[ORDER].ord_upload_date,101), convert(varchar(5),[ORDER].ord_upload_time,114)  FROM [ORDER]  WHERE order_id=" + order_id;

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0);//Receivephotos
                if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//Completeset
                if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2);//exterioronly
                if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3);//uploadby
                if (!reader.IsDBNull(4)) rgb.strC5 = reader.GetString(4);//uploaddate
                if (!reader.IsDBNull(5)) rgb.strC6 = reader.GetString(5);//uploadtime
                object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;

    }

    public static int saveIdComps(int orderid)
    {
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = DB.OpenConnection();
            string now = DateTime.Now.ToString();
            string q = "INSERT INTO comparables (order_id)  VALUES  (" + orderid + ")";
            SqlCommand insert = new SqlCommand(q, conn);
            insert.ExecuteNonQuery();
            result = 1;
            conn.Close();
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace);
        }
        return result;

    }


    public static int updateComps(int order_id, string beds, string baths, string sqft, string lot, string built, string type, string unit, string stories, string data, string docu1, string value, string repaired, string date, string s1, string s2, string s3, string l1, string l2, string l3, string docu2, string procby, string proc, string dateproc, string timeproc, int comp_id, string listed, string saletype, string mls, string salesprice, string comments, string revcompleted, string docu3, string docu4)
    {
        int result = 0;

        SqlConnection conn = null;
        SqlCommand comm = null;

        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "UPDATE   comparables SET  bed = @beds, bath = @baths, sqft = @sqft, lot = @lot, built = @built, type = @type, unit = @unit, stories = @stories, data = @data,  asisvalue = @value, repaired = @repaired, efectivedate = @date, sale1 = @s1, sale2 = @s2, sale3 = @s3, listing1 = @l1, listing2 = @l2, listing3 = @l3, processedby = @procby, processed = @proc, listed = @list, saletype = @stype, mls = @mls, salesprice = @sprice, comments = @comme, revcompleted = @revcom  WHERE (order_id = @idorder AND comp_id = @compid)";
            comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
            comm.Parameters.Add("@compid", SqlDbType.Int).Value = comp_id;
            comm.Parameters.Add("@beds", SqlDbType.VarChar).Value = beds;
            comm.Parameters.Add("@baths", SqlDbType.VarChar).Value = baths;
            comm.Parameters.Add("@sqft", SqlDbType.VarChar).Value = sqft;
            comm.Parameters.Add("@lot", SqlDbType.VarChar).Value = lot;
            comm.Parameters.Add("@built", SqlDbType.VarChar).Value = built;
            comm.Parameters.Add("@type", SqlDbType.VarChar).Value = type;
            comm.Parameters.Add("@unit", SqlDbType.VarChar).Value = unit;
            comm.Parameters.Add("@stories", SqlDbType.VarChar).Value = stories;
            comm.Parameters.Add("@data", SqlDbType.VarChar).Value = data;

            comm.Parameters.Add("@value", SqlDbType.VarChar).Value = value;
            comm.Parameters.Add("@repaired", SqlDbType.VarChar).Value = repaired;

            /*string browser = HttpContext.Current.Request.Browser.Browser;
            string fecha = date;
            if (browser != "IE")
            {
                string[] arr = date.Split('/');
                date = arr[1] + "/" + arr[0] + "/" + arr[2];
            }
            String[] dates= date.Split('/');
            comm.Parameters.Add("@date", SqlDbType.VarChar).Value = dates[1]+"/"+dates[0]+"/"+dates[2];*/
            String[] dates = date.Split('/');
            //comm.Parameters.Add("@date", SqlDbType.VarChar).Value = dates[1] + "/" + dates[0] + "/" + dates[2]; ;
            comm.Parameters.Add("@date", SqlDbType.VarChar).Value = date;
            comm.Parameters.Add("@s1", SqlDbType.VarChar).Value = s1;
            comm.Parameters.Add("@s2", SqlDbType.VarChar).Value = s2;
            comm.Parameters.Add("@s3", SqlDbType.VarChar).Value = s3;
            comm.Parameters.Add("@l1", SqlDbType.VarChar).Value = l1;
            comm.Parameters.Add("@l2", SqlDbType.VarChar).Value = l2;
            comm.Parameters.Add("@l3", SqlDbType.VarChar).Value = l3;
            string[] pro = procby.Split('-');
            procby = pro[0];
            comm.Parameters.Add("@procby", SqlDbType.VarChar).Value = procby;
            comm.Parameters.Add("@proc", SqlDbType.VarChar).Value = proc;
            comm.Parameters.Add("@list", SqlDbType.VarChar).Value = listed;
            comm.Parameters.Add("@stype", SqlDbType.VarChar).Value = saletype;
            comm.Parameters.Add("@mls", SqlDbType.VarChar).Value = mls;
            comm.Parameters.Add("@sprice", SqlDbType.VarChar).Value = salesprice;
            comm.Parameters.Add("@comme", SqlDbType.VarChar).Value = comments;
            comm.Parameters.Add("@revcom", SqlDbType.VarChar).Value = revcompleted;


            comm.ExecuteNonQuery();
            comm.Parameters.Clear();

            string[] name = procby.Split('-');
            /*if (name[0].ToUpper().Equals("FS TEAM"))
            {
                name[0] = "FS";

                comm.CommandText = " update [ORDER] set ord_processor = @proc where order_id = @idorder";
                comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
                comm.Parameters.Add("@proc", SqlDbType.VarChar).Value = name[0].Trim();
                comm.ExecuteNonQuery();
                comm.Parameters.Clear();
            }*/

            if (!docu1.Equals(""))
            {
                try
                {
                    comm.CommandText = "UPDATE   comparables SET   document1 = @docu1  WHERE (order_id = @idorder AND comp_id = @compid)";
                    comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
                    comm.Parameters.Add("@compid", SqlDbType.Int).Value = comp_id;
                    comm.Parameters.Add("@docu1", SqlDbType.VarChar).Value = docu1;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                }
                catch (Exception e1)
                {
                    Utility.writeError("NO actualizo doc1 de comp");

                }
            }

            if (!dateproc.Equals("") && !timeproc.Equals(""))
            {
                try
                {
                    comm.CommandText = "UPDATE  comparables  SET  dateproc = getdate(), timeproc = @timep  WHERE  (order_id = @idorder AND comp_id = @compid)";
                    comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
                    comm.Parameters.Add("@compid", SqlDbType.Int).Value = comp_id;
                    dates = dateproc.Split('/');
                    // comm.Parameters.Add("@datep", SqlDbType.VarChar).Value= dates[1] + "/" + dates[0] + "/" + dates[2];
                    //comm.Parameters.Add("@datep", SqlDbType.VarChar).Value = dateproc;
                    comm.Parameters.Add("@timep", SqlDbType.VarChar).Value = timeproc;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                }
                catch (Exception e)
                {
                    Utility.writeError("No actualizo fecha proc y time proc de comps");
                }
            }

            if (!docu2.Equals(""))
            {
                try
                {
                    comm.CommandText = "UPDATE   comparables SET   document2 = @docu2  WHERE (order_id = @idorder AND comp_id = @compid)";
                    comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
                    comm.Parameters.Add("@compid", SqlDbType.Int).Value = comp_id;
                    comm.Parameters.Add("@docu2", SqlDbType.VarChar).Value = docu2;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                }
                catch (Exception e1)
                {
                    Utility.writeError("NO actualizo doc2 de comp");

                }
            }

            if (!docu3.Equals(""))
            {
                try
                {
                    comm.CommandText = "UPDATE   comparables SET   document3 = @docu3  WHERE (order_id = @idorder AND comp_id = @compid)";
                    comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
                    comm.Parameters.Add("@compid", SqlDbType.Int).Value = comp_id;
                    comm.Parameters.Add("@docu3", SqlDbType.VarChar).Value = docu3;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                }
                catch (Exception e1)
                {
                    Utility.writeError("NO actualizo doc3 de comp");

                }
            }

            if (!docu4.Equals(""))
            {
                try
                {
                    comm.CommandText = "UPDATE   comparables SET   document4 = @docu4  WHERE (order_id = @idorder AND comp_id = @compid)";
                    comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
                    comm.Parameters.Add("@compid", SqlDbType.Int).Value = comp_id;
                    comm.Parameters.Add("@docu4", SqlDbType.VarChar).Value = docu4;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                }
                catch (Exception e1)
                {
                    Utility.writeError("NO actualizo doc4 de comp");

                }
            }

            result = 1;
            int re = SaveProcess("ord_processor", procby, order_id);
        }
        catch (Exception e)
        {
            Utility.writeError("No se pudo agregar a comparables orden: " + order_id + " date: " + date + " ,  " + e.Message + e.StackTrace);
            result = 0;
        }



        conn.Close();
        return result;
    }


    public static RE_GenericBean getComarable(int idorder, int idcomp, int bandera)
    {

        //METODO PARA OBTENER EL ULTIMO COMPARABLE, 0 SI ES EL ORIGINAL(TABLA ORDER) Y 1 SI ES FAILED(TABLA COMPARABLES)
        RE_GenericBean rgb = new RE_GenericBean();
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;
            string select = "";
            string strsql = "";

            if (bandera == 0)
            {
                select = "SELECT   comparables.order_id, comparables.bed, comparables.bath, comparables.sqft, comparables.lot, comparables.built, comparables.type, comparables.unit, comparables.stories, comparables.data, comparables.document1, comparables.asisvalue, comparables.repaired, convert(varchar, comparables.efectivedate,101), comparables.sale1, comparables.sale2, comparables.sale3, comparables.listing1, comparables.listing2, comparables.listing3, comparables.document2, [ORDER].ord_processor, [ORDER].ord_processor_done, [ORDER].ord_agent, [ORDER].ord_agent_done, comparables.listed, comparables.saletype, comparables.mls, comparables.salesprice, comparables.comments, comparables.revcompleted, comparables.document3, comparables.document4 ";
                strsql = select + " FROM  [ORDER] INNER JOIN comparables ON [ORDER].order_id = comparables.order_id  WHERE  (comparables.order_id = " + idorder + ")";
            }

            if (bandera == 1)
            {
                select = "SELECT   order_id, bed, bath, sqft, lot, built, type, unit, stories, data, document1, asisvalue, repaired, convert(varchar, efectivedate,101), sale1, sale2, sale3, listing1, listing2, listing3, document2, processedby, processed, convert(varchar(10), dateproc,101), convert(varchar(5), timeproc,114), listed, saletype, mls, salesprice, comments, revcompleted, document3, document4 ";
                strsql = select + " FROM  comparables  WHERE  (order_id = " + idorder + "  AND  comp_id = " + idcomp + ")";
            }

            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "ordercomps");
            dt = ds.Tables["ordercomps"];
            if (dt.Rows.Count == 0)
            {
                return rgb;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    if (fila[0] != null) rgb.intC1 = int.Parse(fila[0].ToString());  //orden_#
                    if (fila[1] != null) rgb.strC1 = fila[1].ToString(); //bed
                    if (fila[2] != null) rgb.strC2 = fila[2].ToString(); //bath
                    if (fila[3] != null) rgb.strC3 = fila[3].ToString(); //sqft
                    if (fila[4] != null) rgb.strC4 = fila[4].ToString(); //lot
                    if (fila[5] != null) rgb.strC5 = fila[5].ToString();//built
                    if (fila[6] != null) rgb.strC6 = fila[6].ToString();//type
                    if (fila[7] != null) rgb.strC7 = fila[7].ToString();//unit
                    if (fila[8] != null) rgb.strC8 = fila[8].ToString();//stories
                    if (fila[9] != null) rgb.strC9 = fila[9].ToString();//data
                    if (fila[10] != null) rgb.strC10 = fila[10].ToString();//document1
                    if (fila[11] != null) rgb.strC11 = fila[11].ToString();//asisvalue
                    if (fila[12] != null) rgb.strC12 = fila[12].ToString();//repaired
                    if (fila[13] != null) rgb.strC13 = fila[13].ToString();//date
                    if (fila[14] != null) rgb.strC14 = fila[14].ToString();//sale1
                    if (fila[15] != null) rgb.strC15 = fila[15].ToString();//sale2
                    if (fila[16] != null) rgb.strC16 = fila[16].ToString();//sale3
                    if (fila[17] != null) rgb.strC17 = fila[17].ToString();//listing1
                    if (fila[18] != null) rgb.strC18 = fila[18].ToString();//listing2
                    if (fila[19] != null) rgb.strC19 = fila[19].ToString();//listing3
                    if (fila[20] != null) rgb.strC20 = fila[20].ToString(); //document2
                    if (fila[21] != null) rgb.strC21 = fila[21].ToString(); // si bandera=0 guarda procesor order       si bandera=1 guarda new agent failed
                    if (fila[22] != null) rgb.strC22 = fila[22].ToString(); //si bandera=0 guarda procesor_done order   si bandera=1 guarda si es procesada comps
                    if (fila[23] != null) rgb.strC23 = fila[23].ToString(); //si bandera=0 guarda agent order           si bandera=1 guarda date comps
                    if (fila[24] != null) rgb.strC24 = fila[24].ToString(); //si bandera=0 guarda agent_done order      si bandera=1 guarda time comps
                    if (fila[25] != null) rgb.strC25 = fila[25].ToString(); //listed
                    if (fila[26] != null) rgb.strC26 = fila[26].ToString(); //saletype
                    if (fila[27] != null) rgb.strC27 = fila[27].ToString(); //mls
                    if (fila[28] != null) rgb.strC28 = fila[28].ToString(); //salesprice
                    if (fila[29] != null) rgb.strC29 = fila[29].ToString(); //comments
                    if (fila[30] != null) rgb.strC30 = fila[30].ToString(); //revcompleted
                    if (fila[31] != null) rgb.strC31 = fila[31].ToString(); //document3
                    if (fila[32] != null) rgb.strC32 = fila[32].ToString(); //document4
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            return null;

        }


        return rgb;


    }

    public static DataSet getComps(int order_id)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        //result.Tables["Tabla"].Columns.Add("order_id");
        result.Tables["Tabla"].Columns.Add("bed");
        result.Tables["Tabla"].Columns.Add("bath");
        result.Tables["Tabla"].Columns.Add("sqft");
        result.Tables["Tabla"].Columns.Add("lot");
        result.Tables["Tabla"].Columns.Add("built");
        result.Tables["Tabla"].Columns.Add("type");
        result.Tables["Tabla"].Columns.Add("unit");
        result.Tables["Tabla"].Columns.Add("stories");
        result.Tables["Tabla"].Columns.Add("data");
        result.Tables["Tabla"].Columns.Add("document1");
        result.Tables["Tabla"].Columns.Add("asisvalue");
        result.Tables["Tabla"].Columns.Add("repaired");
        result.Tables["Tabla"].Columns.Add("efectivedate");
        result.Tables["Tabla"].Columns.Add("sale1");
        result.Tables["Tabla"].Columns.Add("sale2");
        result.Tables["Tabla"].Columns.Add("sale3");
        result.Tables["Tabla"].Columns.Add("listing1");
        result.Tables["Tabla"].Columns.Add("listing2");
        result.Tables["Tabla"].Columns.Add("listing3");
        result.Tables["Tabla"].Columns.Add("document2");
        result.Tables["Tabla"].Columns.Add("processedby");
        result.Tables["Tabla"].Columns.Add("processed");
        result.Tables["Tabla"].Columns.Add("dateproc");
        result.Tables["Tabla"].Columns.Add("timeproc");
        result.Tables["Tabla"].Columns.Add("listed");
        result.Tables["Tabla"].Columns.Add("saletype");
        result.Tables["Tabla"].Columns.Add("mls");
        result.Tables["Tabla"].Columns.Add("salesprice");
        result.Tables["Tabla"].Columns.Add("comments");
        result.Tables["Tabla"].Columns.Add("document3");
        result.Tables["Tabla"].Columns.Add("document4");

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT  bed, bath, sqft, lot, built, type, unit, stories, data, document1, asisvalue, repaired, convert(varchar(10),efectivedate,101), sale1, sale2, sale3, listing1, listing2, listing3, document2, processedby, processed, convert(varchar(10),dateproc,101), convert(varchar(5),timeproc,114), listed, saletype, mls, salesprice, comments, document3, document4   FROM  comparables  WHERE  (order_id = " + order_id + ")  ORDER BY comp_id desc";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                //if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//order_id
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0);//bed
                if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//bath
                if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2);//sqft
                if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3);//lot
                if (!reader.IsDBNull(4)) rgb.strC5 = reader.GetString(4);//built
                if (!reader.IsDBNull(5)) rgb.strC6 = reader.GetString(5);//type
                if (!reader.IsDBNull(6)) rgb.strC7 = reader.GetString(6);//unit
                if (!reader.IsDBNull(7)) rgb.strC8 = reader.GetString(7);//stories
                if (!reader.IsDBNull(8)) rgb.strC9 = reader.GetString(8);//data
                if (!reader.IsDBNull(9)) rgb.strC10 = reader.GetString(9);//docu1
                if (!reader.IsDBNull(10)) rgb.strC11 = reader.GetString(10);//asisvalue
                if (!reader.IsDBNull(11)) rgb.strC12 = reader.GetString(11);//repair
                if (!reader.IsDBNull(12)) rgb.strC13 = reader.GetString(12);//date
                if (!reader.IsDBNull(13)) rgb.strC14 = reader.GetString(13);//sale1
                if (!reader.IsDBNull(14)) rgb.strC15 = reader.GetString(14);//sale2
                if (!reader.IsDBNull(15)) rgb.strC16 = reader.GetString(15);//sale3
                if (!reader.IsDBNull(16)) rgb.strC17 = reader.GetString(16);//listing1
                if (!reader.IsDBNull(17)) rgb.strC18 = reader.GetString(17);//listing2
                if (!reader.IsDBNull(18)) rgb.strC19 = reader.GetString(18);//listing3
                if (!reader.IsDBNull(19)) rgb.strC20 = reader.GetString(19);//docu2
                if (!reader.IsDBNull(20)) rgb.strC21 = reader.GetString(20);//processedby
                if (!reader.IsDBNull(21)) rgb.strC22 = reader.GetString(21);//processed
                if (!reader.IsDBNull(22)) rgb.strC23 = reader.GetString(22);//dateproc
                if (!reader.IsDBNull(23)) rgb.strC24 = reader.GetString(23);//timeproc
                if (!reader.IsDBNull(24)) rgb.strC25 = reader.GetString(24);//listed
                if (!reader.IsDBNull(25)) rgb.strC26 = reader.GetString(25);//saletype
                if (!reader.IsDBNull(26)) rgb.strC27 = reader.GetString(26);//mls
                if (!reader.IsDBNull(27)) rgb.strC28 = reader.GetString(27);//salesprice
                if (!reader.IsDBNull(28)) rgb.strC29 = reader.GetString(28);//comments
                if (!reader.IsDBNull(29)) rgb.strC30 = reader.GetString(29);//document3
                if (!reader.IsDBNull(30)) rgb.strC31 = reader.GetString(30);//document4
                object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC11, rgb.strC12, rgb.strC13, rgb.strC14, rgb.strC15, rgb.strC16, rgb.strC17, rgb.strC18, rgb.strC19, rgb.strC20, rgb.strC21, rgb.strC22, rgb.strC23, rgb.strC24, rgb.strC25, rgb.strC26, rgb.strC27, rgb.strC28, rgb.strC29, rgb.strC30, rgb.strC31 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        conn.Close();
        return result;
    }

    public static int agregarCompsFail(int id_ord, int order_fail_id)
    {
        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand insert;
        conn = DB.OpenConnection();
        transaction = conn.BeginTransaction();
        int result = 0;

        try
        {

            insert = new SqlCommand();
            insert.Connection = conn;
            insert.CommandType = CommandType.Text;
            insert.Transaction = transaction;

            string q = "INSERT INTO comparables (order_id, order_fail_id)  VALUES  (" + id_ord + ", " + order_fail_id + ")";
            insert.CommandText = q;
            insert.ExecuteNonQuery();
            transaction.Commit();

            result = 1;

        }
        catch (Exception e)
        {
            transaction.Rollback();
            Utility.writeError(e.Message + ", No se genero nuevo comparable");
            result = 0;
        }
        return result;
    }

    public static int getLastCompsbyOrder(int orden)
    {
        int result = 0;

        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select top 1 comp_id from [comparables] where order_id=@orderid order by 1 desc";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetInt32(0); // comp_id
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.Message);
            result = 0;

        }
        return result;
    }

    public static int getFirstCompsbyOrder(int orden)
    {
        int result = 0;

        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select top 1 comp_id from [comparables] where order_id=@orderid order by 1 asc";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetInt32(0); // comp_id
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.Message);
            result = 0;

        }
        return result;
    }

    public static int getLastIDFailProcDrive(int orden, int PD)
    {
        // METODO PARA OBTENER EL ULTIMO FAIL ID SEGUN EL CRITERIO:  0 SI ES PROC O AGENT Y 1 SI ES DRIVER
        int result = 0;
        string cond = "";

        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            if (PD == 0) { cond = "fail_id = 1 OR fail_id = 2"; }
            if (PD == 1) { cond = "fail_id = 3"; }
            if (PD == 2) { cond = "fail_id = 4"; }

            comm.CommandText = "SELECT TOP (1) order_fail_id  FROM  ORDER_FAIL  WHERE  (order_id = @orderid) AND (" + cond + ")  ORDER BY order_fail_id DESC";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = reader.GetInt32(0); // order_fail_id
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.Message);
            result = 0;

        }
        return result;
    }


    // CAMBIAR PROCESOS
    /*public static int clearProcess(int idorder)
    {
        int result = 0;

        SqlConnection conn = null;
        SqlCommand comm = null;

        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "UPDATE    [ORDER] SET  ord_processor_done = @procdone , ord_processor = @proc, ord_qc_done = @qcdone, ord_qc = @qc, ord_agent_done = @agentdone, ord_agent = @agent, ord_submitted_done = @subdone, ord_subby = @subby, ord_driver_done = @driverdone, ord_driver = @driver WHERE   (order_id = @idorder)";
            comm.Parameters.Add("@idorder", SqlDbType.Int).Value = idorder;
            comm.Parameters.Add("@procdone", SqlDbType.VarChar).Value = "NO";
            comm.Parameters.Add("@proc", SqlDbType.VarChar).Value = "";
            comm.Parameters.Add("@qcdone", SqlDbType.VarChar).Value = "NO";
            comm.Parameters.Add("@qc", SqlDbType.VarChar).Value = "";
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
            result = 1;

        }
        catch (Exception e)
        {
            Utility.writeError("No se pudo agregar a addAppointment orden: " + orderid + " " + e.Message);
            result = 0;
        }



        conn.Close();
        return result;
    }*/


    public static DataSet GetAllProcess()
    {//retorna todos los procesos que puede llevar un producto
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("process_id");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("internal");//3

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT  process_id, name, internal  from process  order by name";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //processid
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2);//internal


                object[] objArr = { rgb.intC1, rgb.strC1, rgb.intC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        finally
        {
            if (reader != null) { reader.Dispose(); }
            if (conn != null) { conn.Dispose(); }

        }
        return result;

    }

    public static int addState(string statename, string stateinitial)
    {
        int result = 0;


        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select name from [STATE] where upper(name)=@statenew ";
            comm.Parameters.Add("@statenew", SqlDbType.VarChar).Value = statename.Trim().ToUpper();

            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = 3; // comp_id

            }
            reader.Close();
            reader.Dispose();
            comm.Parameters.Clear();
            if (result != 3)
            {
                comm.CommandText = "insert into [STATE] (name,initial, enable) values (@statenew, @initial, 1)";
                comm.Parameters.Add("@statenew", SqlDbType.VarChar).Value = statename.Trim().ToUpper();
                comm.Parameters.Add("@initial", SqlDbType.VarChar).Value = stateinitial.Trim().ToUpper();

                comm.ExecuteNonQuery();
                result = 1;
            }
            else
            {
                comm.Parameters.Clear();
                comm.CommandText = "update [STATE] set enable=1 where upper(name)=@statenew";
                comm.Parameters.Add("@statenew", SqlDbType.VarChar).Value = statename.Trim().ToUpper();
                comm.ExecuteNonQuery();
                result = 1;

            }
            conn.Close();

        }
        catch (Exception e)
        {

            Utility.writeError(e.Message);
            result = 0;

        }

        return result;
    }

    public static int addCounty(string stateid, string countyname, string countyinitial)
    {
        int result = 0;


        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select name from [COUNTY] where upper(name)=@countyname and state_id=@stateid ";
            comm.Parameters.Add("@countyname", SqlDbType.VarChar).Value = countyname.Trim().ToUpper();
            comm.Parameters.Add("@stateid", SqlDbType.Int).Value = stateid;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result = 3; // comp_id

            }
            reader.Close();
            reader.Dispose();
            comm.Parameters.Clear();
            if (result != 3)
            {
                comm.CommandText = "insert into [COUNTY] (name,initial, enable, state_id) values (@statenew, @initial, 1, @stateid)";
                comm.Parameters.Add("@statenew", SqlDbType.VarChar).Value = countyname.Trim().ToUpper();
                comm.Parameters.Add("@initial", SqlDbType.VarChar).Value = countyinitial.Trim().ToUpper();
                comm.Parameters.Add("@stateid", SqlDbType.Int).Value = stateid;

                comm.ExecuteNonQuery();
                result = 1;
            }
            else
            {
                comm.Parameters.Clear();
                comm.CommandText = "update [COUNTY] set enable=1 where upper(name)=@countyname and state_id=@stateid";
                comm.Parameters.Add("@countyname", SqlDbType.VarChar).Value = countyname.Trim().ToUpper();
                comm.Parameters.Add("@stateid", SqlDbType.Int).Value = stateid;
                comm.ExecuteNonQuery();
                result = 1;

            }
            conn.Close();
            comm.Dispose();
        }
        catch (Exception e)
        {

            Utility.writeError(e.Message);
            result = 0;

        }

        return result;
    }

    public static int deletePhoto(int photoid)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        try
        {

            conn = OpenConnection();
            SqlDataReader reader;
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "delete from [PHOTO] where photo_id=@photoid ";
            comm.Parameters.Add("@photoid", SqlDbType.Int).Value = photoid;
            comm.ExecuteNonQuery();
            result = 1;

        }
        catch (Exception e)
        {


        }
        finally
        {
            if (conn != null)
            {
                conn.Close(); conn.Dispose();
            }
            if (comm != null)
            {
                comm.Dispose();
            }


        }
        return result;


    }

    public static int deleteLoginAcc(int id)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        try
        {

            conn = OpenConnection2();
            SqlDataReader reader;
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "delete from [tbl_acc_login] where id=@id ";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = id;
            comm.ExecuteNonQuery();
            result = 1;

        }
        catch (Exception e)
        {
            Utility.writeError("Error deleteLogin "+e.Message+" "+e.Source);

        }
        finally
        {
            if (conn != null)
            {
                conn.Close(); conn.Dispose();
            }
            if (comm != null)
            {
                comm.Dispose();
            }


        }
        return result;


    }
    public static int updateQCSub(int order_id, string qcheck, string qagent, string qdate, string qtime, string q1, string q2, string q3, string q4, string q5, string q6int1, string q6int2, string q7, string q8, string q9, string submitted, string subby, string subdate, string subtime, string comment, string q10, string revcheck)
    {
        //if(qcheck=="Select One"){qcheck="Select One";}
        if (qagent == "Select One") { qagent = ""; }
        if (q1 == "Select One") { q1 = ""; }
        if (q2 == "Select One") { q2 = ""; }
        if (q3 == "Select One") { q3 = ""; }
        if (q4 == "Select One") { q4 = ""; }
        if (q5 == "Select One") { q5 = ""; }
        if (q7 == "Select One") { q7 = ""; }
        if (q8 == "Select One") { q8 = ""; }
        if (q9 == "Select One") { q9 = ""; }
        if (q10 == "Select One") { q10 = ""; }
        if (subby == "Select One") { subby = ""; }
        if (submitted == "Select One") { submitted = ""; }
        if (revcheck == "Select One") { revcheck = ""; }

        int result = 0;

        SqlConnection conn = null;
        SqlCommand comm = null;

        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;


            comm.CommandText = "UPDATE QCSUB  SET  qcheck = @qcheck, qagent = @qagent, q1 = @q1, q2 = @q2, q3 = @q3, q4 = @q4, q5 = @q5, q6int1 = @q6int1, q6int2 = @q6int2, q7 = @q7, q8 = @q8, q9 = @q9, submitted = @submitted, subby = @subby, comment = @comment, q10 = @q10, rev_check=@revch  WHERE  (order_id = @idorder)";
            comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
            comm.Parameters.Add("@qcheck", SqlDbType.VarChar).Value = qcheck;
            comm.Parameters.Add("@qagent", SqlDbType.VarChar).Value = qagent;

            comm.Parameters.Add("@q1", SqlDbType.VarChar).Value = q1;
            comm.Parameters.Add("@q2", SqlDbType.VarChar).Value = q2;
            comm.Parameters.Add("@q3", SqlDbType.VarChar).Value = q3;
            comm.Parameters.Add("@q4", SqlDbType.VarChar).Value = q4;
            comm.Parameters.Add("@q5", SqlDbType.VarChar).Value = q5;
            comm.Parameters.Add("@q6int1", SqlDbType.VarChar).Value = q6int1;
            comm.Parameters.Add("@q6int2", SqlDbType.VarChar).Value = q6int2;
            comm.Parameters.Add("@q7", SqlDbType.VarChar).Value = q7;
            comm.Parameters.Add("@q8", SqlDbType.VarChar).Value = q8;
            comm.Parameters.Add("@q9", SqlDbType.VarChar).Value = q9;
            comm.Parameters.Add("@submitted", SqlDbType.VarChar).Value = submitted;
            comm.Parameters.Add("@subby", SqlDbType.VarChar).Value = subby;
            comm.Parameters.Add("@comment", SqlDbType.VarChar).Value = comment;
            comm.Parameters.Add("@q10", SqlDbType.VarChar).Value = q10;
            comm.Parameters.Add("@revch", SqlDbType.VarChar).Value = revcheck;

            comm.ExecuteNonQuery();
            comm.Parameters.Clear();

            if (!qdate.Equals("") && !qtime.Equals(""))
            {
                try
                {
                    comm.CommandText = "UPDATE  QCSUB  SET  qdate = getdate(), qtime = @qtime  WHERE  (order_id = @idorder)";
                    comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
                    //comm.Parameters.Add("@qdate", SqlDbType.Date).Value = qdate;
                    comm.Parameters.Add("@qtime", SqlDbType.VarChar).Value = qtime;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                }
                catch (Exception e)
                {
                    Utility.writeError("No actualizo fecha qcsub y time qcsub de qc/submitted");
                    Utility.writeError(e.Message + e.StackTrace);
                }
            }

            if (!subdate.Equals("") && !subtime.Equals(""))
            {
                try
                {
                    comm.CommandText = "UPDATE  QCSUB  SET  subdate = getdate(), subtime = @subtime  WHERE  (order_id = @idorder)";
                    comm.Parameters.Add("@idorder", SqlDbType.Int).Value = order_id;
                    //comm.Parameters.Add("@subdate", SqlDbType.Date).Value = subdate;
                    comm.Parameters.Add("@subtime", SqlDbType.VarChar).Value = subtime;

                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                }
                catch (Exception e)
                {
                    Utility.writeError("No actualizo fecha qcsub y time qcsub de qc/submitted");
                    Utility.writeError(e.Message + e.StackTrace);
                }
            }

            result = 1;

        }
        catch (Exception e)
        {
            Utility.writeError("No se pudo agregar a qc/submitted orden: " + order_id + " date: " + subdate + " ,  " + e.Message + e.StackTrace);
            Utility.writeError(e.Message + e.StackTrace);
            result = 0;
        }



        conn.Close();
        return result;
    }

    public static RE_GenericBean getQCSub(int idorder)
    {

        RE_GenericBean rgb = new RE_GenericBean();
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter sqladapt;
            string select = "";
            string strsql = "";

            select = "SELECT   qcheck, qagent, convert(varchar(10), qdate,101), convert(varchar(5), qtime, 114), q1, q2, q3, q4, q5, q6int1, q6int2, q7, q8, q9, submitted, subby, convert(varchar(10), subdate,101), convert(varchar(5), subtime,114), comment, documentsub, q10, rev_check, dataacurate";
            strsql = select + " FROM  QCSUB  WHERE  (order_id = " + idorder + ")";

            sqladapt = new SqlDataAdapter(strsql, conn);
            sqladapt.Fill(ds, "orderqcsub");
            dt = ds.Tables["orderqcsub"];
            if (dt.Rows.Count == 0)
            {
                return rgb;
            }
            else
            {
                foreach (DataRow fila in dt.Rows)
                {
                    if (fila[0] != null) rgb.strC1 = fila[0].ToString(); //qcheck
                    if (fila[1] != null) rgb.strC2 = fila[1].ToString(); //qagent
                    if (fila[2] != null) rgb.strC3 = fila[2].ToString(); //qdate
                    if (fila[3] != null) rgb.strC4 = fila[3].ToString(); //qtime
                    if (fila[4] != null) rgb.strC5 = fila[4].ToString();//q1
                    if (fila[5] != null) rgb.strC6 = fila[5].ToString();//q2
                    if (fila[6] != null) rgb.strC7 = fila[6].ToString();//q3
                    if (fila[7] != null) rgb.strC8 = fila[7].ToString();//q4
                    if (fila[8] != null) rgb.strC9 = fila[8].ToString();//q5
                    if (fila[9] != null) rgb.strC10 = fila[9].ToString();//q6int1
                    if (fila[10] != null) rgb.strC11 = fila[10].ToString();//q6int2
                    if (fila[11] != null) rgb.strC12 = fila[11].ToString();//q7
                    if (fila[12] != null) rgb.strC13 = fila[12].ToString();//q8
                    if (fila[13] != null) rgb.strC14 = fila[13].ToString();//q9
                    if (fila[14] != null) rgb.strC15 = fila[14].ToString();//submitted
                    if (fila[15] != null) rgb.strC16 = fila[15].ToString();//subby
                    if (fila[16] != null) rgb.strC17 = fila[16].ToString();//subdate
                    if (fila[17] != null) rgb.strC18 = fila[17].ToString();//subtime
                    if (fila[18] != null) rgb.strC19 = fila[18].ToString();//comment
                    if (fila[19] != null) rgb.strC20 = fila[19].ToString();//documentsub
                    if (fila[20] != null) rgb.strC21 = fila[20].ToString();//q10
                    if (fila[21] != null) rgb.strC22 = fila[21].ToString();//rev_check
                    if (fila[22] != null) rgb.strC23 = fila[22].ToString();//dataacurate
                }
            }
            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.StackTrace);
            return null;

        }


        return rgb;


    }

    public static DataSet getAllCounties()
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("county");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("enable");//3
        result.Tables["Tabla"].Columns.Add("initial");//4


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT county_id, name, enable, initial FROM COUNTY  WHERE     (enable = 1) order by 2";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //county_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2); //enable
                if (!reader.IsDBNull(3)) rgb.strC2 = reader.GetString(3);//initial



                object[] objArr = { rgb.intC1, rgb.strC1, rgb.intC2, rgb.strC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;

    }
    public static int getCountDue(string fecha, string where)
    {//devuelve el conteo de Due segun la fecha y where enviados
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            //comm.CommandText = "select count(*) from (SELECT ord_id, ord_due, ord_time, ord_source, ord_source2, ord_type, ord_street_number, ord_street_name, ord_city, ord_zip, ord_county, (CASE WHEN ord_failed='Y' THEN ord_newproc ELSE ord_procesor END) as ord_procesor, (CASE WHEN ord_failed='Y' THEN ord_newcompleted ELSE ord_completed END) as ord_completed, ord_driver, ord_pics, ord_qc, (CASE WHEN ord_failed='Y' THEN ord_resubmitted ELSE ord_submitted END) as ord_submitted , ord_contact_info, ord_int, ord_comments, ord_order, ord_failed, ord_newcompleted, ord_resubmitted, ord_sector fROM tbl_order where ord_due>CURRENT_TIMESTAMP - 31) as orden where ord_submitted='N' and ord_due='" + fecha + "'" + where;
            comm.CommandText = "select count(*) from (" + where + ") orden  where    (orden.ord_submit ='NO' OR orden.ord_submit is null) and (orden.duedate = '" + fecha;

            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        finally
        {
            if (rs != null)
            {
                rs.Dispose();
                rs.Close();
            }
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }
    public static int getCountDue_processed(string fecha, string where)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            //comm.CommandText = "select count(*) from (SELECT ord_id, ord_due, ord_time, ord_source, ord_source2, ord_type, ord_street_number, ord_street_name, ord_city, ord_zip, ord_county, (CASE WHEN ord_failed='Y' THEN ord_newproc ELSE ord_procesor END) as ord_procesor, (CASE WHEN ord_failed='Y' THEN ord_newcompleted ELSE ord_completed END) as ord_completed, ord_driver, ord_pics, ord_qc, (CASE WHEN ord_failed='Y' THEN ord_resubmitted ELSE ord_submitted END) as ord_submitted , ord_contact_info, ord_int, ord_comments, ord_order, ord_failed, ord_newcompleted, ord_resubmitted, ord_sector fROM tbl_order where ord_due>CURRENT_TIMESTAMP - 31) as orden where ord_submitted='N' and ord_completed='Y' and ord_due='" + fecha + "'" + where;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where ((orden.ord_processor_done ='YES' or orden.ord_processor_done='N/A') and (orden.ord_failed is null or orden.ord_failed = 'NO') and (orden.ord_driver_done ='NO' or orden.ord_driver_done is null) and UPPER(orden.status)='PENDING' and (orden.duedate ='" + fecha + ")";

            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        finally
        {
            if (rs != null)
            {
                rs.Dispose();
                rs.Close();
            }
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }

    public static int getReady(string fecha, string where)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            //comm.CommandText = "select count(*) from (SELECT ord_id, ord_due, ord_time, ord_source, ord_source2, ord_type, ord_street_number, ord_street_name, ord_city, ord_zip, ord_county, (CASE WHEN ord_failed='Y' THEN ord_newproc ELSE ord_procesor END) as ord_procesor, (CASE WHEN ord_failed='Y' THEN ord_newcompleted ELSE ord_completed END) as ord_completed, ord_driver, ord_pics, ord_qc, (CASE WHEN ord_failed='Y' THEN ord_resubmitted ELSE ord_submitted END) as ord_submitted , ord_contact_info, ord_int, ord_comments, ord_order, ord_failed, ord_newcompleted, ord_resubmitted, ord_sector fROM tbl_order where ord_due>CURRENT_TIMESTAMP - 31) as orden where ord_completed='N' and ord_procesor<>'' and ord_procesor is not null and  ord_due='" + fecha + "'" + where;

            comm.CommandText = "select count(*) from ( " + where + " ) orden where orden.status='PENDING' and  (orden.duedate ='" + fecha + "  and (orden.ord_failed is null or orden.ord_failed = 'NO')  and ((orden.ord_driver_done='YES' and orden.ord_processor_done='YES') or (orden.ord_driver_done='YES' and orden.ord_processor_done='N/A') or (orden.ord_driver_done='N/A' and orden.ord_processor_done='YES') or (orden.ord_driver_done='N/A' and orden.ord_processor_done='N/A'))";

            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }
    public static int getAssigned(string fecha, string where)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where  (orden.ord_processor <> '' and orden.ord_processor is not null) and (ord_processor_done = 'NO' OR ord_processor_done IS NULL)  and   UPPER(orden.status)='PENDING'  and (orden.ord_failed='NO' or orden.ord_failed is null ) and (orden.duedate ='" + fecha;
            // comm.CommandText = "select count(*) from ( " + where + " ) tablita where tablita.status='PENDING'  and  tablita.duedate='" + fecha + "'  and (tablita.ord_failed is null or tablita.ord_failed = 'NO') and (tablita.ord_processor <> '') and ((tablita.ord_processor_done = 'NO' and tablita.ord_driver_done = 'NO') or (tablita.ord_processor_done = 'NO' and tablita.ord_driver_done is null) or (tablita.ord_processor_done is null and tablita.ord_driver_done = 'NO') or (tablita.ord_processor_done is null and tablita.ord_driver_done is null) or (tablita.ord_processor_done = 'N/A' and tablita.ord_driver_done = 'NO') or (tablita.ord_processor_done = 'N/A' and tablita.ord_driver_done is null) or (tablita.ord_processor_done = 'NO' and tablita.ord_driver_done = 'N/A'))";
            // comm.CommandText = "select count(*) from ("+ where +" ) tablita WHERE (tablita.ord_processor_done ='YES') and  tablita.ord_processor_done <> 'N/A' 	and (tablita.ord_driver_done ='NO' or tablita.ord_driver_done is null or tablita.ord_driver_done <> 'N/A') 	and UPPER(tablita.status)='PENDING'  and (tablita.ord_failed='NO' or tablita.ord_failed is null )";
            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int getUnAssigned(string fecha, string where)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            //comm.CommandText = "select count(*) from (SELECT ord_id, ord_due, ord_time, ord_source, ord_source2, ord_type, ord_street_number, ord_street_name, ord_city, ord_zip, ord_county, (CASE WHEN ord_failed='Y' THEN ord_newproc ELSE ord_procesor END) as ord_procesor, (CASE WHEN ord_failed='Y' THEN ord_newcompleted ELSE ord_completed END) as ord_completed, ord_driver, ord_pics, ord_qc, (CASE WHEN ord_failed='Y' THEN ord_resubmitted ELSE ord_submitted END) as ord_submitted , ord_contact_info, ord_int, ord_comments, ord_order, ord_failed, ord_newcompleted, ord_resubmitted, ord_sector fROM tbl_order where ord_due>CURRENT_TIMESTAMP - 31) as orden where ord_completed='N' and ord_procesor<>'' and ord_procesor is not null and  ord_due='" + fecha + "'" + where;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where orden.status='PENDING' and (orden.ord_processor='' OR orden.ord_processor is  null )  and  (orden.duedate ='" + fecha;

            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int getCountDue_processedPhotos(string fecha, string where)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where ((orden.ord_driver_done ='YES' or orden.ord_driver_done='N/A') and (orden.ord_processor_done ='NO' or orden.ord_processor_done is null) and (orden.ord_failed is null or orden.ord_failed = 'NO') and UPPER(orden.status)='PENDING' and (orden.duedate ='" + fecha + ")";

            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        finally
        {
            if (rs != null)
            {
                rs.Dispose();
                rs.Close();
            }
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }

    public static int getAssignedPhotos(string fecha, string where)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where  (orden.ord_driver <> '' and orden.ord_driver is not null) and (ord_driver_done = 'NO' OR ord_driver_done IS NULL)  and   UPPER(orden.status)='PENDING'  and (orden.ord_failed='NO' or orden.ord_failed is null ) and (orden.duedate ='" + fecha;
            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int getUnAssignedPhotos(string fecha, string where)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where orden.status='PENDING' and (orden.ord_driver='' OR orden.ord_driver is  null )  and  (orden.duedate ='" + fecha;

            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int getPhoto(string where, string wherephoto)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select count(*) from ( " + where + " ) orden " + wherephoto;
            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int getProcessed(string where)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where orden.status='PENDING' and  (orden.ord_failed is null or orden.ord_failed = 'NO')  and (orden.ord_processor_done='YES' or orden.ord_processor_done= 'N/A')";
            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int getPendingClient(string where)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where orden.status='PENDING' ";
            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int getCompletedClient(string where)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            where = where.Replace("(Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN') and", "");
            where = where.Replace("(Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN')and", "");
            where = where.Replace("( STATUS.name='pending' and Upper(STATUS.name) <>'PAID') and", "");
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where orden.status='COMPLETED' ";
            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int getCancelledClient(string where)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            where = where.Replace("(Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN') and", "");
            where = where.Replace("(Upper(STATUS.name)='PENDING' or Upper(STATUS.name)='ASSIGN')and", "");
            where = where.Replace("( STATUS.name='pending' and Upper(STATUS.name) <>'PAID') and", "");
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select count(*) from ( " + where + " ) orden where orden.status='CANCELLED' ";
            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int getFailed(string where, string wherefail)
    {
        int result = 0;
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader rs = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            //comm.CommandText = "select count(*) from (SELECT ord_id, ord_due, ord_time, ord_source, ord_source2, ord_type, ord_street_number, ord_street_name, ord_city, ord_zip, ord_county, (CASE WHEN ord_failed='Y' THEN ord_newproc ELSE ord_procesor END) as ord_procesor, (CASE WHEN ord_failed='Y' THEN ord_newcompleted ELSE ord_completed END) as ord_completed, ord_driver, ord_pics, ord_qc, (CASE WHEN ord_failed='Y' THEN ord_resubmitted ELSE ord_submitted END) as ord_submitted , ord_contact_info, ord_int, ord_comments, ord_order, ord_failed, ord_newcompleted, ord_resubmitted, ord_sector fROM tbl_order where ord_due>CURRENT_TIMESTAMP - 31) as orden where ord_completed='N' and ord_procesor<>'' and ord_procesor is not null and  ord_due='" + fecha + "'" + where;
            comm.CommandText = "select count(*) from  (" + where + ") orden   "+wherefail;

            rs = comm.ExecuteReader();
            if (rs.Read())
            {
                if (!rs.IsDBNull(0)) result = rs.GetInt32(0);
            }
            rs.Dispose();
            rs.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
            return 0;
        }
        return result;
    }

    public static int changeDuedate(string s1)
    {
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = DB.OpenConnection();
            string q = "update [ORDER] set duedate = @date1  WHERE (product_id = 2 or product_id = 7) and (DATEDIFF(day, duedate, GETDATE() + 1) >= 0) and (appdate = '' or appdate is null) and (ord_submitted_done = 'NO' OR ord_submitted_done is null) ";
            SqlCommand insert = new SqlCommand(q, conn);
            insert.Parameters.Add("@date1", SqlDbType.Date).Value = s1;
            insert.ExecuteNonQuery();
            conn.Close();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace + e.Message);
        }
        return result;
    }
    public static int changeDuedateMasivo(ArrayList array, string date) {
        int result = 0;
        try
        {
            SqlConnection conn = null;
            conn = DB.OpenConnection();

            foreach (int orderid in array)
            {
                string q = "update [ORDER] set duedate = @date1,  comments = 'Duedate:' + CONVERT(varchar, duedate, 101) + ' ' + comments   WHERE order_id =@orderid  and (DATEDIFF(day,  GETDATE(), @date1) >= 0)  and (ord_submitted_done = 'NO' OR ord_submitted_done is null) ";
                SqlCommand insert = new SqlCommand(q, conn);
                insert.Parameters.Add("@date1", SqlDbType.Date).Value = date;
                insert.Parameters.Add("@orderid", SqlDbType.Int).Value = orderid;
                insert.ExecuteNonQuery();

            }
            conn.Close();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.StackTrace + e.Message);
        }
        return result;
    
    }
    public static int assignOrder(string campotbl, string valor, string criterio, int valorcriterio, int tipo, int parperfil, string campodone)
    {
        //devuelve valor string de un ampo determinado de una orden determinada, tipo=0 es string,  tipo=1 es int, tipo=2 date, tipo=3 fecha
        // parper es el parametro que indica que perfil es el encargad de realizar el cambio a guardar en ese campo 2= driver, 3= proc sr.
        //campodone es el nombre del campo que almacena si el trabajo ya fue hecho por alguien en la orden
        int result = 0;

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        ArrayList procesos = new ArrayList();

        try
        {
            int bandera1 = 0; int bandera2 = 1; string processname = ""; int perfil = -1;
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            //busco la orden y veo que procesos tiene segun el producto
            comm.CommandText = "SELECT PROCESS.name, PROCESS.perfil FROM  [ORDER] INNER JOIN PRODUCT ON [ORDER].product_id = PRODUCT.product_id INNER JOIN PRODUCTS_PROCESS ON PRODUCT.product_id = PRODUCTS_PROCESS.product_id INNER JOIN PROCESS ON PRODUCTS_PROCESS.process_id = PROCESS.process_id WHERE  ([ORDER].order_id = @orden)";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = valorcriterio;
            reader = comm.ExecuteReader();
            comm.Parameters.Clear();
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) processname = reader.GetString(0);
                if (!reader.IsDBNull(1)) perfil = reader.GetInt32(1);
                procesos.Add(processname);
                if (perfil == parperfil) { bandera1 = 1; }
            }

            // si la orden si se le puede asignar persona para ese proceso 
            if (bandera1 == 1)
            {
                int status = 0;
                string summit = "";
                reader.Dispose();
                reader.Close();
                processname = "";
                comm.CommandText = "SELECT " + campodone + " AS campo, status_id, ord_submitted_done  FROM  [ORDER] WHERE  (order_id = @orden)";
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = valorcriterio;
                reader = comm.ExecuteReader();
                comm.Parameters.Clear();
                if (reader.Read())
                {
                    if (!reader.IsDBNull(0)) processname = reader.GetString(0);
                    if (!reader.IsDBNull(1)) status = reader.GetInt32(1);
                    if (!reader.IsDBNull(2)) summit = reader.GetString(2);

                    string per = null;
                    rUser user = (rUser)HttpContext.Current.Session["userid"];
                    if (user != null)
                        per = user.getPerfilId();

                    if (campotbl == "ord_qc")
                    {
                        if (status != 1 || summit.ToUpper() == "YES") bandera2 = 0;
                    }
                    else if (campotbl == "ord_driver")
                    {
                        if (per != "24" && processname.ToUpper().Equals("YES")) bandera2 = 0;
                    }
                    else if (processname.ToUpper().Equals("YES")) bandera2 = 0;

                }
                reader.Dispose();
                reader.Close();
                //ahora veo si bandera2=1 es porque no ha sido registrado como terminado el proceso entonce
                //actualizo el campo

                if (bandera2 != 0)
                {
                    //veo si es difetente el que tiene al que se le va a aponer entonces envio correo
                    comm.CommandText = "select " + campotbl + " from [ORDER] where " + criterio + " =@orden";
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = valorcriterio;
                    reader = comm.ExecuteReader();
                    string processorname = "";
                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0)) processorname = reader.GetString(0);
                    }

                    reader.Dispose();
                    comm.Parameters.Clear();

                    if (!processorname.ToUpper().Equals(valor))
                    {
                        comm.CommandText = "update [ORDER] set " + campotbl + "= @valor where " + criterio + "=@orden ";
                        comm.Parameters.Add("@orden", SqlDbType.Int).Value = valorcriterio;
                        if (tipo == 0)
                        {
                            comm.Parameters.Add("@valor", SqlDbType.VarChar).Value = valor;
                        }
                        if (tipo == 1)
                        {
                            comm.Parameters.Add("@valor", SqlDbType.Int).Value = valor;
                        }
                        comm.ExecuteNonQuery();
                        result = 1;

                        comm.Parameters.Clear();
                        if (result == 1)
                        {
                            if (campotbl == "ord_processor")
                            {
                                saveValueCampoTabla("processedby", "comparables", valor, "order_id", valorcriterio, 0);
                            }
                            if (campotbl == "ord_qc")
                            {
                                saveValueCampoTabla("qagent", "QCSUB", valor, "order_id", valorcriterio, 0);
                                if (processname.ToUpper().Equals("YES"))
                                {
                                    int r1 = SaveProcess("ord_qc_done", "NO", valorcriterio);
                                    int r2 = SaveProcess("ord_qc_date", "", valorcriterio);
                                    int r3 = SaveProcess("ord_qc_time", "", valorcriterio);
                                    if (r1 == 1)
                                    {

                                        saveValueCampoTabla("qcheck", "QCSUB", "No", "order_id", valorcriterio, 0);
                                        saveValueCampoTabla("qdate", "QCSUB", "", "order_id", valorcriterio, 0);
                                        saveValueCampoTabla("qtime", "QCSUB", "", "order_id", valorcriterio, 0);
                                    }
                                }
                            }
                        }
                    }
                    //pongo precio a la orden
                    com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                    string strvendor = service.getTodosDatosUsuarioAlias(valor);
                    // Utility.writeError(DateTime.Now + " cadena del webservice = " + strvendor);
                    rUser uservendor = Utility.getRUser(strvendor);
                    if (uservendor.prices != null)
                    {
                        foreach (RE_GenericBean obj in uservendor.prices)
                        {
                            int p = obj.intC1;
                            string pp = obj.strC1;
                            foreach (string str in procesos)
                            {
                                if (str.ToUpper().Equals("PHOTOS EXT") && p == 1)
                                {
                                    int res6 = DB.SaveProcess("driver_fee", pp, valorcriterio);
                                }
                                if (str.ToUpper().Equals("PHOTOS INT") && p == 9)
                                {
                                    int res6 = DB.SaveProcess("driver_fee", pp, valorcriterio);
                                }
                            }

                        }
                    }
                }
            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            result = 0;
        }
        finally
        {
            conn.Close();
            comm.Dispose();
            conn.Close();
            conn.Dispose();
        }
        return result;

    }
    public static string getOrderNum(int number, string criterio, int valorcriterio)
    {
        //devuelve valor string de un ampo determinado de una orden determinada, tipo=0 es string,  tipo=1 es int, tipo=2 date, tipo=3 fecha
        // parper es el parametro que indica que perfil es el encargad de realizar el cambio a guardar en ese campo 2= driver, 3= proc sr.
        //campodone es el nombre del campo que almacena si el trabajo ya fue hecho por alguien en la orden
        string result = "";

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;

        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            //obteniendo orden#

            comm.CommandText = "select  ordernum from [ORDER]  where " + criterio + "=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = valorcriterio;
            reader = comm.ExecuteReader();
            string ordernum = "";
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) ordernum = reader.GetString(0);
                result = ordernum;
            }
            reader.Dispose();
            comm.Parameters.Clear();
        }
        catch (Exception ex)
        {

        }
        return result;
    }

    public static DataSet getProcProducts()
    {//devuelve los procesos ya asignados a todos los productos
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("ID");//product id
        result.Tables["Tabla"].Columns.Add("PRODUCT", typeof(RE_GenericBean));//product name

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT   PRODUCTS_PROCESS.product_id, PROCESS.name, PROCESS.perfil, PROCESS.process_id   FROM    PRODUCT INNER JOIN   PRODUCTS_PROCESS ON PRODUCT.product_id = PRODUCTS_PROCESS.product_id INNER JOIN   PROCESS ON PRODUCTS_PROCESS.process_id = PROCESS.process_id   ORDER BY PRODUCTS_PROCESS.orden";
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//product_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2);//perfil de quien puede hacer ese proceso
                if (!reader.IsDBNull(3)) rgb.intC3 = reader.GetInt32(3);//id del producto de process
                object[] objarr = { rgb.intC1, rgb };
                result.Tables["Tabla"].Rows.Add(objarr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }


    public static DataSet getProcsVendorDate(int orden)
    {//devuelve los datos de los procesos de los productos
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("ID");//process id
        result.Tables["Tabla"].Columns.Add("NAME");//process name
        result.Tables["Tabla"].Columns.Add("INFO", typeof(RE_GenericBean));//product name

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;

        SqlConnection conn1 = null;
        SqlCommand comm1 = null;
        SqlDataReader reader1 = null;


        try
        {
            conn1 = OpenConnection();
            comm1 = new SqlCommand();
            comm1.Connection = conn1;
            comm1.CommandType = CommandType.Text;

            comm1.CommandText = "SELECT     ord_driver, ord_driver_done, convert(varchar(10),ord_upload_date,101), convert(varchar(5),ord_upload_time,114), ord_processor, ord_processor_done, convert(varchar(10),ord_processor_date,101), convert(varchar(5),ord_processor_time,114), ord_qc, ord_qc_done, convert(varchar(10),ord_qc_date,101), convert(varchar(5),ord_qc_time,114), ord_agent, ord_agent_done, convert(varchar(10),ord_agent_date,101), convert(varchar(5),ord_agent_time,114), ord_subby, ord_submitted_done, convert(varchar(10),ord_submitted_date,101), convert(varchar(5),ord_submitted_time,114), ord_resubby, ord_resubomitted_done, ord_dataqc, ord_dataqc_done, convert(varchar(10),ord_qc_date,101) AS Expr1, convert(varchar(5),ord_qc_time,114) AS Expr2  FROM   [ORDER]  WHERE order_id=@orden ";
            comm1.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader1 = comm1.ExecuteReader();
            RE_GenericBean rgb1 = null;
            while (reader1.Read())
            {
                rgb1 = new RE_GenericBean();
                if (!reader1.IsDBNull(0)) rgb1.strC1 = reader1.GetString(0);//ord_driver
                if (!reader1.IsDBNull(1)) rgb1.strC2 = reader1.GetString(1);//ord_driver_done
                if (!reader1.IsDBNull(2)) rgb1.strC3 = reader1.GetString(2);//ord_driver_date
                if (!reader1.IsDBNull(3)) rgb1.strC4 = reader1.GetString(3);//ord_driver_time
                if (!reader1.IsDBNull(4)) rgb1.strC5 = reader1.GetString(4);//ord_processor
                if (!reader1.IsDBNull(5)) rgb1.strC6 = reader1.GetString(5);//ord_processor_done
                if (!reader1.IsDBNull(6)) rgb1.strC7 = reader1.GetString(6);//ord_processor_date
                if (!reader1.IsDBNull(7)) rgb1.strC8 = reader1.GetString(7);//ord_processor_time
                if (!reader1.IsDBNull(8)) rgb1.strC9 = reader1.GetString(8);//ord_qc
                if (!reader1.IsDBNull(9)) rgb1.strC10 = reader1.GetString(9);//ord_qc_done
                if (!reader1.IsDBNull(10)) rgb1.strC11 = reader1.GetString(10);//ord_qc_date
                if (!reader1.IsDBNull(11)) rgb1.strC12 = reader1.GetString(11);//ord_qc_time
                if (!reader1.IsDBNull(12)) rgb1.strC13 = reader1.GetString(12);//ord_agent
                if (!reader1.IsDBNull(13)) rgb1.strC14 = reader1.GetString(13);//ord_agent_done
                if (!reader1.IsDBNull(14)) rgb1.strC15 = reader1.GetString(14);//ord_agent_date
                if (!reader1.IsDBNull(15)) rgb1.strC16 = reader1.GetString(15);//ord_agent_time
                if (!reader1.IsDBNull(16)) rgb1.strC17 = reader1.GetString(16);//ord_subby
                if (!reader1.IsDBNull(17)) rgb1.strC18 = reader1.GetString(17);//ord_submitted_done
                if (!reader1.IsDBNull(18)) rgb1.strC19 = reader1.GetString(18);//ord_submitted_date
                if (!reader1.IsDBNull(19)) rgb1.strC20 = reader1.GetString(19);//ord_submitted_time
                if (!reader1.IsDBNull(20)) rgb1.strC21 = reader1.GetString(20);//ord_resubby
                if (!reader1.IsDBNull(21)) rgb1.strC22 = reader1.GetString(21);//ord_resubomitted_done
                if (!reader1.IsDBNull(22)) rgb1.strC23 = reader1.GetString(22);//ord_dataqc
                if (!reader1.IsDBNull(23)) rgb1.strC24 = reader1.GetString(23);//ord_dataqc_done
                if (!reader1.IsDBNull(24)) rgb1.strC25 = reader1.GetString(24);//ord_qc_date
                if (!reader1.IsDBNull(25)) rgb1.strC26 = reader1.GetString(25);//ord_qc_time
            }
            reader1.Close();

            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT     process_id, name  FROM   PROCESS";
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//process_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//process name

                if (rgb.strC1.ToUpper() == "PHOTOS EXT" || rgb.strC1.ToUpper() == "PHOTOS INT" || rgb.strC1.ToUpper() == "REKEY WITH PHOTOS")
                {
                    rgb.strC2 = rgb1.strC1; rgb.strC3 = rgb1.strC2; rgb.strC4 = rgb1.strC3; rgb.strC5 = rgb1.strC4;
                }
                else if (rgb.strC1.ToUpper() == "DATA ENTRY")
                {
                    rgb.strC2 = rgb1.strC5; rgb.strC3 = rgb1.strC6; rgb.strC4 = rgb1.strC7; rgb.strC5 = rgb1.strC8;
                }
                else if (rgb.strC1.ToUpper() == "QC CHECK")
                {
                    rgb.strC2 = rgb1.strC9; rgb.strC3 = rgb1.strC10; rgb.strC4 = rgb1.strC11; rgb.strC5 = rgb1.strC12;
                }
                else if (rgb.strC1.ToUpper() == "COMP SEARCH")
                {
                    rgb.strC2 = rgb1.strC13; rgb.strC3 = rgb1.strC14; rgb.strC4 = rgb1.strC15; rgb.strC5 = rgb1.strC16;
                }
                else if (rgb.strC1.ToUpper() == "SUBMITTED")
                {
                    rgb.strC2 = rgb1.strC17; rgb.strC3 = rgb1.strC18; rgb.strC4 = rgb1.strC19; rgb.strC5 = rgb1.strC20;
                }
                else if (rgb.strC1.ToUpper() == "RESUBMITTED")
                {
                    rgb.strC2 = rgb1.strC21; rgb.strC3 = rgb1.strC22; rgb.strC4 = rgb1.strC19; rgb.strC5 = rgb1.strC20;
                }
                else if (rgb.strC1.ToUpper() == "DATA ENTRY QC")
                {
                    rgb.strC2 = rgb1.strC23; rgb.strC3 = rgb1.strC24; rgb.strC4 = rgb1.strC25; rgb.strC5 = rgb1.strC26;
                }

                object[] objarr = { rgb.intC1, rgb.strC1, rgb };
                result.Tables["Tabla"].Rows.Add(objarr);
            }
            reader.Close();
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }

    public static float getFee(string tablename, string columnname, string criterio, string valorcriterio)
    {
        float result = -1;

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT cast( (case WHEN [" + tablename + "]." + columnname + " IS NULL THEN -1 ELSE [" + tablename + "]." + columnname + " END) as varchar)  from [" + tablename + "] where " + criterio + " = @criterio ";
            comm.Parameters.Add("@criterio", SqlDbType.Int).Value = valorcriterio;
            reader = comm.ExecuteReader();
            string cadena = "";
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) cadena = reader.GetString(0);//product_id
                result = float.Parse(cadena);

            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return -1;
        }
        finally
        {
            conn.Close();

        }




        return result;

    }

    public static double findProductFee(string product)
    {
        double result;
        result = 0.0;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select cast(client_fee as varchar) from product where product_id=@productid";
            comm.Parameters.Add("@productid", SqlDbType.VarChar).Value = product;
            reader = comm.ExecuteReader();
            string cadena = "";
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) cadena = reader.GetString(0);//fee
                result = double.Parse(cadena);
            }


        }
        catch (Exception ex)
        {
            result = -1.0;

        }
        finally
        {
            conn.Close();
            reader.Dispose();

        }
        return result;

    }

    public static DataSet getDatosbyZip(string zipcode)
    {

        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("state");//state
        result.Tables["Tabla"].Columns.Add("area");//sector
        result.Tables["Tabla"].Columns.Add("county_id");//county
        result.Tables["Tabla"].Columns.Add("sector_id");//county
        result.Tables["Tabla"].Columns.Add("sector_name");//county
        result.Tables.Add("cities");
        result.Tables["cities"].Columns.Add("city");//cities name
        result.Tables["cities"].Columns.Add("cityid");//cities id
        RE_GenericBean rg;
        SqlCommand comm = null;

        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT   CITY.name AS city, STATE.state_id AS state, ZIPCODE.area_id, COUNTY.county_id, SECTOR_AREA.sector_id, SECTOR.name, CITY.city_id  FROM    CITY INNER JOIN   COUNTY ON CITY.county_id = COUNTY.county_id INNER JOIN  STATE ON COUNTY.state_id = STATE.state_id INNER JOIN   ZIPCODE ON CITY.city_id = ZIPCODE.city INNER JOIN SECTOR ON STATE.state_id = SECTOR.state_id INNER JOIN  SECTOR_AREA ON ZIPCODE.area_id = SECTOR_AREA.area_id AND SECTOR.sector_id = SECTOR_AREA.sector_id WHERE        (ZIPCODE.zipcode = @zipcode)";
            comm.Parameters.Add("@zipcode", SqlDbType.Int).Value = zipcode;
            reader = comm.ExecuteReader();
            int cont = 0;
            while (reader.Read())
            {
                rg = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rg.strC1 = reader.GetString(0);//city
                if (!reader.IsDBNull(1)) rg.intC1 = reader.GetInt32(1);//state
                if (!reader.IsDBNull(2)) rg.intC2 = reader.GetInt32(2);//area
                if (!reader.IsDBNull(3)) rg.intC3 = reader.GetInt32(3);//county
                if (!reader.IsDBNull(4)) rg.intC4 = reader.GetInt32(4);//sector
                if (!reader.IsDBNull(5)) rg.strC2 = reader.GetString(5);//sector
                if (!reader.IsDBNull(6)) rg.intC5 = reader.GetInt32(6);//city_id
                if (cont == 0)
                {
                    object[] objarr = { rg.intC1, rg.intC2, rg.intC3, rg.intC4, rg.strC2 };
                    result.Tables["Tabla"].Rows.Add(objarr);
                }
                cont++;

                object[] objarr2 = { rg.strC1, rg.intC5 };
                result.Tables["cities"].Rows.Add(objarr2);
            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();

        }



        return result;
    }
    public static DataSet getAreas()
    {

        DataSet result = new DataSet();
        RE_GenericBean rgb = null;
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("area_id");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("enable");//2
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT area_id, name, enable FROM AREA  WHERE  enable =1";
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//area_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2);//enable
                object[] objArr = { rgb.intC1, rgb.strC1, rgb.intC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            conn.Close();
            if (reader != null)
                reader.Dispose();

        }



        return result;
    }

    public static DataSet getSectors()
    {

        DataSet result = new DataSet();
        RE_GenericBean rgb = null;
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("sector_id");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("enable");//2
        result.Tables["Tabla"].Columns.Add("state_id");//2
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT sector_id, name, enable, state_id FROM SECTOR  WHERE  enable =1";
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//sector_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2);//enable
                if (!reader.IsDBNull(3)) rgb.intC3 = reader.GetInt32(3);//enable
                object[] objArr = { rgb.intC1, rgb.strC1, rgb.intC2, rgb.intC3 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            conn.Close();
            reader.Dispose();

        }



        return result;
    }
    //AB devuelve el invoice de driver, procesador, QC 
    // where:  filtoros de la consulta, string periodo de fechas currency modnada, fee:  el valor a mostrar en el fee
    public static REPORTDS getInvoice(string where, string periodo, string totalfee, string currency, string parametro, string style, Byte[] imagen, string pfee)
    {


        REPORTDS result = new REPORTDS();
        RE_GenericBean rgb = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        string rxml = null;
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        rxml = service.getCompanies();
        DataSet dscompany = null;

        if (!rxml.Equals("") || rxml != null)
        {
            dscompany = Utility.getCompanies(rxml);
        }
        DataSet usuarios = (DataSet)HttpContext.Current.Session["Usuarios"];
        DataSet usuVendor = (DataSet)HttpContext.Current.Session["usuVendor"];
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            string fee = " fee ";
            string campofail = "orden.ord_failed";
            if (parametro.Equals("driver"))
            {
                //fee = "  CASE WHEN orden.company = 1  THEN orden.fee ELSE orden.psfprice END ";
                fee = pfee;
                campofail = "orden.ord_failed_driver";
            }
            else if (parametro.Equals("processor"))
            {
                campofail = "orden.ord_failed_processor";
            }
            else if (parametro.Equals("orden.ord_failed_qc"))
            {
                campofail = "orden.ord_failed_qc";
            }
            if (!where.Equals(""))
            {
                where = " WHERE " + where;
                if (!parametro.Equals("photos") && !parametro.Equals("client"))
                {
                    where = where + " and (orden.ord_" + parametro + " <> 'CXL'  and orden.ord_" + parametro + " <> '' and orden.ord_" + parametro + "_done= 'YES' )";
                }

            }
            else
            {
                if (!parametro.Equals("photos"))
                {
                    where = " WHERE (orden.ord_" + parametro + " <> 'CXL'  and orden.ord_" + parametro + " <> '')";
                }
                else
                {
                    where = " WHERE orden.ord_driver <> 'CXL' and orden.ord_driver <>''";
                }
            }

            comm.CommandType = CommandType.Text;
            if (parametro.Equals("photos"))
            {
                comm.CommandText = "SELECT orden.order_id, ordernum, client_id,  company, stnum, stadd, stcity, status_id, ''  AS FAIL, " + fee + ",   ord_uploadby  as Processor, CONVERT(VARCHAR(8),orden.ord_upload_date, 1) as date, PRODUCT.initial , ofail.fail_id, ord_driver  FROM [ORDER] orden  INNER JOIN PRODUCT ON orden.product_id = PRODUCT.product_id LEFT OUTER JOIN  ( Select  OA.order_id, OA.fail_id  from ORDER_FAIL as OA, ( SELECT  order_id, MIN(order_fail_id) as order_fail_id FROM  ORDER_FAIL  where fail_id= 1 group by order_id ) as tabla where tabla.order_fail_id = OA.order_fail_id ) AS ofail ON orden.order_id = ofail.order_id     " + where + " order by 11,12";
            }
            else if (parametro.Equals("qc"))
            {
                string select = "SELECT orden.order_id, ordernum, client_id,  company, stnum, stadd, stcity, status_id, CASE WHEN " + campofail + " IS NULL THEN '' ELSE 'Y' END AS FAIL, " + fee + ", orden.ord_qc as Processor,  CONVERT(VARCHAR(8),orden.ord_qc_date, 1)  as date, PRODUCT.initial , ofail.fail_id, ord_processor, ord_reprocessor, ord_reqc  FROM [ORDER] orden  INNER JOIN PRODUCT ON orden.product_id = PRODUCT.product_id LEFT OUTER JOIN  ( Select  OA.order_id, OA.fail_id  from ORDER_FAIL as OA, ( SELECT  order_id, MIN(order_fail_id) as order_fail_id FROM  ORDER_FAIL  where fail_id= 4 group by order_id ) as tabla where tabla.order_fail_id = OA.order_fail_id ) AS ofail ON orden.order_id = ofail.order_id ";
                comm.CommandText = select + where + " order by 11,12";
            }
            else if (parametro.Equals("client"))
            {
                comm.CommandText = "SELECT orden.order_id, ordernum, client_id,  company, stnum, stadd, stcity, case when orden.status_id=1 then 'Pending' when orden.status_id = 3 then 'Completed' when  orden.status_id= 4 then 'Cancelled' end, CONVERT(VARCHAR(8), orden.ord_submitted_date,1), paid from [order] orden " + where + " and (orden.status_id= 4 or orden.status_id=3)  order by 9";
            }
            else
            {


                comm.CommandText = "SELECT orden.order_id, ordernum, client_id,  company, stnum, stadd, stcity, status_id, CASE WHEN " + campofail + " IS NULL THEN '' ELSE 'Y' END AS FAIL, " + fee + ", CASE WHEN " + campofail + " IS NULL THEN  orden.ord_" + parametro + " ELSE orden.ord_" + parametro + " END as Processor, CASE WHEN " + campofail + " IS NULL then  CONVERT(VARCHAR(8),orden.ord_" + parametro + "_date, 1) ELSE CONVERT(VARCHAR(8), orden.ord_" + parametro + "_date,1) END as date, PRODUCT.initial , ofail.fail_id, ord_processor  FROM [ORDER] orden  INNER JOIN PRODUCT ON orden.product_id = PRODUCT.product_id LEFT OUTER JOIN  ( Select  OA.order_id, OA.fail_id  from ORDER_FAIL as OA, ( SELECT  order_id, MIN(order_fail_id) as order_fail_id FROM  ORDER_FAIL  where fail_id= 1 group by order_id ) as tabla where tabla.order_fail_id = OA.order_fail_id ) AS ofail ON orden.order_id = ofail.order_id     " + where + " order by 11,12";
            }
            reader = comm.ExecuteReader();
            Utility.writeError("Invoice Driver  select: "+comm.CommandText);
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//order_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//order_num
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//client_id
                if (!reader.IsDBNull(3)) rgb.intC2 = reader.GetInt32(3);//company 
                if (!reader.IsDBNull(4)) rgb.strC4 = reader.GetString(4);//stnum 
                if (!reader.IsDBNull(5)) rgb.strC5 = reader.GetString(5);//stadd 
                if (!reader.IsDBNull(6)) rgb.strC6 = reader.GetString(6);//stcity
                if (!reader.IsDBNull(7)) rgb.intC3 = reader.GetInt32(7);//status_id
                if (!reader.IsDBNull(8)) rgb.strC7 = reader.GetString(8);//ord_failed
                if (!reader.IsDBNull(9)) rgb.strC8 = reader.GetFloat(9).ToString();//fee 
                if (!reader.IsDBNull(10)) rgb.strC9 = reader.GetString(10).ToString();//ord_proc
                if (!reader.IsDBNull(11)) rgb.strC10 = reader.GetString(11).ToString();//ord_proc_date
                if (!reader.IsDBNull(12)) rgb.strC12 = reader.GetString(12).ToString();//ord_type
                if (!reader.IsDBNull(13)) rgb.strC13 = reader.GetInt32(13).ToString();//ord_fail_type
                if (!reader.IsDBNull(14)) rgb.strC14 = reader.GetString(14);//ord_processor (ord_driver)

                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.intC2.ToString()))
                        {
                            rgb.strC11 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }
                if (usuarios == null)
                {
                    string rxml1 = service.getPerfiles(1, 1);
                    DataSet perfiles = Utility.getPerfiles(rxml1);
                    HttpContext.Current.Session["Perfiles"] = perfiles;
                    usuarios = Utility.getTodosUsuarios(rxml1);

                }

                if (usuarios != null)
                {
                    for (int ii = 0; ii <= (usuarios.Tables[0].Rows.Count - 1); ii++)
                    {
                        string initial = usuarios.Tables[0].Rows[ii]["alias"].ToString();
                        // if (parametro.Equals("photos"))
                        //{
                        string initial2 = usuarios.Tables[0].Rows[ii]["user"].ToString();

                        //}

                        if (initial.Equals(rgb.strC9) || initial2.Equals(rgb.strC9))
                        {
                            rgb.strC9 = usuarios.Tables[0].Rows[ii]["name"].ToString() + " " + usuarios.Tables[0].Rows[ii]["lastname"].ToString();
                            rgb.strC15 = usuarios.Tables[0].Rows[ii]["profilename"].ToString();
                        }
                        if (initial.Equals(rgb.strC14))
                        {
                            rgb.strC14 = usuarios.Tables[0].Rows[ii]["name"].ToString() + " " + usuarios.Tables[0].Rows[ii]["lastname"].ToString();

                        }
                    }
                }
                // busc a proc o driver


                if (usuVendor != null)
                {
                    for (int ii = 0; ii <= (usuVendor.Tables[0].Rows.Count - 1); ii++)
                    {
                        string initial = usuVendor.Tables[0].Rows[ii]["alias"].ToString();

                        if (initial.Equals(rgb.strC9))
                        {
                            rgb.strC9 = usuVendor.Tables[0].Rows[ii]["name"].ToString() + " " + usuVendor.Tables[0].Rows[ii]["lastname"].ToString(); ;
                            rgb.strC15 = usuVendor.Tables[0].Rows[ii]["profilename"].ToString();
                        }
                        if (initial.Equals(rgb.strC14))
                        {
                            rgb.strC14 = usuVendor.Tables[0].Rows[ii]["name"].ToString() + " " + usuVendor.Tables[0].Rows[ii]["lastname"].ToString();

                        }
                    }
                }

                //si la orden esta fallada voy a traer el agente, date, failid del fallo 


                result.order.AddorderRow(rgb.intC1.ToString(), rgb.strC1, rgb.strC2.ToString(), rgb.strC11, rgb.strC4, rgb.strC5, rgb.strC6, rgb.intC3.ToString(), rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC12, rgb.strC13, rgb.strC14, rgb.strC15);

            }

            result.datos.AdddatosRow(periodo, totalfee, currency, style, parametro, imagen);
        }
        catch (Exception ex)
        {
            result = null;
            Utility.writeError(ex.Message + ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();
        }




        return result;
    }

    public static REPORTDS getInvoiceClient(string where, string periodo, string totalfee, string currency, string parametro, string style, Byte[] imagen)
    {


        REPORTDS result = new REPORTDS();
        RE_GenericBean rgb = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        string rxml = null;
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        rxml = service.getCompanies();
        DataSet dscompany = null;

        if (!rxml.Equals("") || rxml != null)
        {
            dscompany = Utility.getCompanies(rxml);
        }
        DataSet usuarios = (DataSet)HttpContext.Current.Session["Usuarios"];
        DataSet usuVendor = (DataSet)HttpContext.Current.Session["usuVendor"];
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            string fee = "fee";
            string campofail = "orden.ord_failed";
            if (!where.Equals(""))
            {
                where = " WHERE " + where;


            }


            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT orden.order_id, ordernum, client_id, product.name, stnum, stadd, stcity, zip, case when orden.status_id=1 then 'Pending' when orden.status_id = 3 then 'Completed' when  orden.status_id= 4 then 'Cancelled' when orden.status_id = 5 then 'Paid' end, CONVERT(VARCHAR(8), orden.ord_submitted_date,1), case when client_id = 'PACIFICSTAR' then convert(varchar,convert(decimal(20,2), psfprice)) else convert(varchar,convert(decimal(20,2), fee)) end fee, case when paid='YES' then 'YES' else '' end, orden.account from [order] orden, product " + where + " and (orden.status_id= 4 or orden.status_id=3 or orden.status_id=5 or orden.status_id=1) and orden.product_id= product.product_id order by 3,10 desc";
            Utility.writeError(" Invoice Client Query "+comm.CommandText);
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//order_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//order_num
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//client_id
                if (!reader.IsDBNull(3)) rgb.strC3 = reader.GetString(3);//product name
                if (!reader.IsDBNull(4)) rgb.strC4 = reader.GetString(4);//stnum
                if (!reader.IsDBNull(5)) rgb.strC5 = reader.GetString(5);//stadd 
                if (!reader.IsDBNull(6)) rgb.strC6 = reader.GetString(6);//stcity 
                if (!reader.IsDBNull(7)) rgb.strC7 = reader.GetString(7);//zipcode
                if (!reader.IsDBNull(8)) rgb.strC8 = reader.GetString(8);//status_id
                if (!reader.IsDBNull(9)) rgb.strC9 = reader.GetString(9);//submitted_date
                if (!reader.IsDBNull(10)) rgb.strC10 = reader.GetString(10); //fee
                if (!reader.IsDBNull(11)) rgb.strC11 = reader.GetString(11);//paid
                if (!reader.IsDBNull(12)) rgb.strC12 = reader.GetInt32(12).ToString();//account


                Utility.setVariablesSession();
                DataSet dsaccount = (DataSet)HttpContext.Current.Session["accounts"];
                //buscando el account
                if (dsaccount != null)
                {
                    for (int ii = 0; ii <= (dsaccount.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccount.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC12.ToString()))
                        {
                            rgb.strC12 = dsaccount.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }
                //si la orden esta fallada voy a traer el agente, date, failid del fallo 


                result.order.AddorderRow(rgb.intC1.ToString(), rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC11, rgb.strC12, "", "", "");

            }

            result.datos.AdddatosRow(periodo, totalfee, currency, style, parametro, imagen);
        }
        catch (Exception ex)
        {
            result = null;
            Utility.writeError(ex.Message + ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();
        }




        return result;
    }



    public static REPORTDS getInvoiceQC(string pwhere, string periodo, string totalfee, string currency, string parametro, string style, Byte[] imagen, string name, string date1, string date2)
    {


        string where = "";
        REPORTDS result = new REPORTDS();
        RE_GenericBean rgb = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        string rxml = null;
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        rxml = service.getCompanies();
        DataSet dscompany = null;

        if (!rxml.Equals("") || rxml != null)
        {
            dscompany = Utility.getCompanies(rxml);
        }
        DataSet usuarios = (DataSet)HttpContext.Current.Session["Usuarios"];
        DataSet usuVendor = (DataSet)HttpContext.Current.Session["usuVendor"];
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            string fee = "fee";
            string campofail = "orden.ord_failed";

            if (parametro.Equals("qc"))
            {
                campofail = "orden.ord_failed_qc";
            }


            comm.CommandType = CommandType.Text;
            for (int i = 0; i < 4; i++)
            {

                if (i == 0)
                {
                    // obteniendo los qc
                    where = "";
                    string select = "SELECT orden.order_id, ordernum, client_id,  company, stnum, stadd, stcity, status_id, CASE WHEN orden.ord_failed_qc IS NULL THEN '' ELSE 'Y' END AS FAIL, fee, orden.ord_qc as Processor,  CONVERT(VARCHAR(8),orden.ord_qc_date, 1)  as date, PRODUCT.initial , ofail.fail_id, ord_processor  FROM [ORDER] orden  INNER JOIN PRODUCT ON orden.product_id = PRODUCT.product_id LEFT OUTER JOIN  ( Select  OA.order_id, OA.fail_id  from ORDER_FAIL as OA, ( SELECT  order_id, MIN(order_fail_id) as order_fail_id FROM  ORDER_FAIL  where (fail_id= 4 or fail_id= 1 or fail_id= 5 or fail_id= 2 ) group by order_id ) as tabla where tabla.order_fail_id = OA.order_fail_id ) AS ofail ON orden.order_id = ofail.order_id ";
                    where = " WHERE  orden.ord_qc_done='YES' ";
                    if (style.Equals("General")) { name = ""; }
                    if (!name.Equals("")) { where = where + " and orden.ord_qc = '" + name + "'"; }

                    where = where + " and (orden.ord_qc <> 'CXL'  and orden.ord_qc <> '')";


                    if (!date1.Equals("")) { if (!where.Equals(" WHERE ")) { where += " and "; } where = where + "  orden.ord_qc_date >= '" + date1 + "' "; }

                    if (!date2.Equals("")) { if (!where.Equals(" WHERE ")) { where += " and "; } where = where + "  orden.ord_qc_date<= '" + date2 + "' "; }
                    comm.CommandText = select + where + " order by 11,12";
                }
                else

                    if (i == 1)
                    {// obteniendo los proc
                        where = "";
                        string select = "SELECT orden.order_id, ordernum, client_id,  company, stnum, stadd, stcity, status_id, CASE WHEN " + campofail + " IS NULL THEN '' ELSE 'Y' END AS FAIL, " + fee + ", orden.ord_processor as Processor,  CONVERT(VARCHAR(8),orden.ord_processor_date, 1)  as date, PRODUCT.initial , ofail.fail_id, ord_processor  FROM [ORDER] orden  INNER JOIN PRODUCT ON orden.product_id = PRODUCT.product_id LEFT OUTER JOIN  ( Select  OA.order_id, OA.fail_id  from ORDER_FAIL as OA, ( SELECT  order_id, MIN(order_fail_id) as order_fail_id FROM  ORDER_FAIL  where (fail_id= 4 or fail_id= 1 or fail_id= 5 or fail_id= 2 ) group by order_id ) as tabla where tabla.order_fail_id = OA.order_fail_id ) AS ofail ON orden.order_id = ofail.order_id ";
                        if (!pwhere.Equals(""))
                        {
                            where = " WHERE " + pwhere;
                            if (!name.Equals("")) { where = where + " and orden.ord_processor = '" + name + "'"; }
                        }
                        else
                        {
                            where = " WHERE (orden.ord_processor <> 'CXL'  and orden.ord_processor <> '')";
                            if (!name.Equals("")) { where = where + " and orden.ord_processor = '" + name + "'"; }
                        }
                        comm.CommandText = select + where + " order by 11,12";
                    }
                    else
                        if (i == 2)
                        {
                            // obteniendo los qc del fallo
                            where = "";

                            string select = "SELECT orden.order_id, orden.ordernum, orden.client_id, orden.company, orden.stnum, orden.stadd, orden.stcity, orden.status_id, CASE WHEN [ord_failed_qc] IS NULL THEN '' ELSE 'Y' END AS FAIL, orden.fee, ORDER_FAIL.qc AS Processor, CONVERT(VARCHAR(8),   ORDER_FAIL.qc_date, 1) AS date, PRODUCT.initial,6, orden.ord_processor FROM  [ORDER] AS orden INNER JOIN  PRODUCT ON orden.product_id = PRODUCT.product_id INNER JOIN  ORDER_FAIL ON orden.order_id = ORDER_FAIL.order_id";
                            if (!pwhere.Equals(""))
                            {
                                where = " WHERE ";
                                if (!name.Equals("")) { where = where + "  (ORDER_FAIL.qc =  '" + name + "')"; }

                                if (!date1.Equals("")) { if (!where.Equals(" WHERE ")) { where += " and "; } where = where + "  [ORDER_FAIL].qc_date>= '" + date1 + "' "; }

                                if (!date2.Equals("")) { if (!where.Equals(" WHERE ")) { where += " and "; } where = where + "  [ORDER_FAIL].qc_date<= '" + date2 + "' "; }
                            }









                            comm.CommandText = select + where + " order by 11,12";
                        }

                        else
                            if (i == 3)
                            {
                                // obteniendo los new agent del fallo
                                where = "";
                                string select = "SELECT orden.order_id, orden.ordernum, orden.client_id, orden.company, orden.stnum, orden.stadd, orden.stcity, orden.status_id, CASE WHEN [ord_failed_qc] IS NULL THEN '' ELSE 'Y' END AS FAIL, orden.fee, ORDER_FAIL.agent AS Processor, CONVERT(VARCHAR(8),   ORDER_FAIL.agent_date, 1) AS date, PRODUCT.initial,6, orden.ord_processor FROM  [ORDER] AS orden INNER JOIN  PRODUCT ON orden.product_id = PRODUCT.product_id INNER JOIN  ORDER_FAIL ON orden.order_id = ORDER_FAIL.order_id";
                                if (!pwhere.Equals(""))
                                {
                                    where = " WHERE ";
                                    if (!name.Equals("")) { where = where + "  (ORDER_FAIL.agent =  '" + name + "')"; }

                                    if (!date1.Equals("")) { if (!where.Equals(" WHERE ")) { where += " and "; } where = where + "  [ORDER_FAIL].agent_date>= '" + date1 + "' "; }

                                    if (!date2.Equals("")) { if (!where.Equals(" WHERE ")) { where += " and "; } where = where + "  [ORDER_FAIL].agent_date<= '" + date2 + "' "; }
                                }

                                comm.CommandText = select + where + " order by 11,12";
                            }

                reader = comm.ExecuteReader();

                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//order_id
                    if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//order_num
                    if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//client_id
                    if (!reader.IsDBNull(3)) rgb.intC2 = reader.GetInt32(3);//company 
                    if (!reader.IsDBNull(4)) rgb.strC4 = reader.GetString(4);//stnum 
                    if (!reader.IsDBNull(5)) rgb.strC5 = reader.GetString(5);//stadd 
                    if (!reader.IsDBNull(6)) rgb.strC6 = reader.GetString(6);//stcity
                    if (!reader.IsDBNull(7)) rgb.intC3 = reader.GetInt32(7);//status_id
                    if (!reader.IsDBNull(8)) rgb.strC7 = reader.GetString(8);//ord_failed
                    if (!reader.IsDBNull(9)) rgb.strC8 = reader.GetFloat(9).ToString();//fee 
                    if (!reader.IsDBNull(10)) rgb.strC9 = reader.GetString(10).ToString();//ord_proc
                    if (!reader.IsDBNull(11)) rgb.strC10 = reader.GetString(11).ToString();//ord_proc_date
                    if (!reader.IsDBNull(12)) rgb.strC12 = reader.GetString(12).ToString();//ord_type
                    if (!reader.IsDBNull(13)) rgb.strC13 = reader.GetInt32(13).ToString();//ord_fail_type
                    if (!reader.IsDBNull(14)) rgb.strC14 = reader.GetString(14);//ord_processor (ord_driver)

                    if (i == 0) { rgb.strC1 = rgb.strC1 + " QC"; }
                    // if (i == 1) { rgb.strC1 = rgb.strC1 + " RQC"; }
                    if (i == 1) { rgb.strC1 = rgb.strC1 + " PRO"; }
                    if (i == 2) { rgb.strC1 = rgb.strC1 + " QCF"; }
                    if (i == 3) { rgb.strC1 = rgb.strC1 + " NEWAG"; }


                    //buscando la compania
                    if (dscompany != null)
                    {
                        for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                        {
                            if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.intC2.ToString()))
                            {
                                rgb.strC11 = dscompany.Tables[0].Rows[ii][1].ToString();
                            }
                        }
                    }
                    if (usuarios == null)
                    {
                        string rxml1 = service.getPerfiles(1, 1);
                        DataSet perfiles = Utility.getPerfiles(rxml1);
                        HttpContext.Current.Session["Perfiles"] = perfiles;
                        usuarios = Utility.getTodosUsuarios(rxml1);

                    }

                    if (usuarios != null)
                    {
                        for (int ii = 0; ii <= (usuarios.Tables[0].Rows.Count - 1); ii++)
                        {
                            string initial = usuarios.Tables[0].Rows[ii]["alias"].ToString();

                            if (initial.Equals(rgb.strC9))
                            {
                                rgb.strC9 = usuarios.Tables[0].Rows[ii]["name"].ToString() + " " + usuarios.Tables[0].Rows[ii]["lastname"].ToString();
                                rgb.strC15 = usuarios.Tables[0].Rows[ii]["profilename"].ToString();
                            }
                            if (initial.Equals(rgb.strC14))
                            {
                                rgb.strC14 = usuarios.Tables[0].Rows[ii]["name"].ToString() + " " + usuarios.Tables[0].Rows[ii]["lastname"].ToString();

                            }
                        }
                    }


                    //si la orden esta fallada voy a traer el agente, date, failid del fallo 

                    if (rgb.strC15.Equals("QC Analist 1") || rgb.strC15.Equals("QC Analyst 2") || rgb.strC15.Equals("QC Manager"))
                    {
                        result.order.AddorderRow(rgb.intC1.ToString(), rgb.strC1, rgb.strC2.ToString(), rgb.strC11, rgb.strC4, rgb.strC5, rgb.strC6, rgb.intC3.ToString(), rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC12, rgb.strC13, rgb.strC14, rgb.strC15);
                    }

                }
                reader.Close();

            }
            result.datos.AdddatosRow(periodo, totalfee, currency, style, parametro, imagen);
        }
        catch (Exception ex)
        {
            result = null;
            Utility.writeError(ex.Message + ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();
        }




        return result;
    }

    public static REPORTDS getSourceReport(string where, string periodo, string totalfee, string currency, string parametro, string style, Byte[] imagen, string campofee)
    {


        REPORTDS result = new REPORTDS();
        RE_GenericBean rgb = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        string rxml = null;
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        rxml = service.getCompanies();
        DataSet dscompany = null;

        if (!rxml.Equals("") || rxml != null)
        {
            dscompany = Utility.getCompanies(rxml);
        }
        Utility.setVariablesSession();
        DataSet dsaccount = (DataSet)HttpContext.Current.Session["accounts"];

        DataSet usuarios = (DataSet)HttpContext.Current.Session["Usuarios"];
        DataSet usuVendor = (DataSet)HttpContext.Current.Session["usuVendor"];
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            string fee = "fee";
            string campofail = "orden.ord_failed";
            campofee = " CASE WHEN orden.company = 1  THEN orden.fee ELSE orden.psfprice END ";
            if (!where.Equals(""))
            {
                where = " WHERE " + where;
                if (parametro.Equals("ord_submitted"))
                {
                    where = where + " and (orden.ord_submitted_done = 'YES' )";
                }

            }

            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT orden.order_id, ordernum, client_id,  company, stnum, stadd, stcity, status_id, case when ord_failed is not null then 'Y' else '' end  AS FAIL, " + campofee + ",   CONVERT(VARCHAR(8),orden." + parametro + ", 1) as date, PRODUCT.initial ,account, case when paid = 'YES' then 'Y' else '' end as paid   FROM [ORDER] orden  INNER JOIN PRODUCT ON orden.product_id = PRODUCT.product_id  " + where + " order by 11,12";

            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//order_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//order_num
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//client_id
                if (!reader.IsDBNull(3)) rgb.intC2 = reader.GetInt32(3);//company 
                if (!reader.IsDBNull(4)) rgb.strC3 = reader.GetString(4);//stnum 
                if (!reader.IsDBNull(5)) rgb.strC4 = reader.GetString(5);//stadd 
                if (!reader.IsDBNull(6)) rgb.strC5 = reader.GetString(6);//stcity
                if (!reader.IsDBNull(7)) rgb.intC3 = reader.GetInt32(7);//status_id
                if (!reader.IsDBNull(8)) rgb.strC6 = reader.GetString(8);//ord_failed
                if (!reader.IsDBNull(9)) rgb.strC7 = reader.GetFloat(9).ToString();//fee 
                if (!reader.IsDBNull(10)) rgb.strC8 = reader.GetString(10).ToString();//ord_date
                if (!reader.IsDBNull(11)) rgb.strC9 = reader.GetString(11).ToString();//ord_type
                if (!reader.IsDBNull(12)) rgb.intC4 = reader.GetInt32(12);//account
                if (!reader.IsDBNull(13)) rgb.strC10 = reader.GetString(13);//paid

                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.intC2.ToString()))
                        {
                            rgb.strC11 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }
                //buscando el account
                if (dsaccount != null)
                {
                    for (int ii = 0; ii <= (dsaccount.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccount.Tables[0].Rows[ii][0].ToString().Equals(rgb.intC4.ToString()))
                        {
                            rgb.strC12 = dsaccount.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }





                //si la orden esta fallada voy a traer el agente, date, failid del fallo 


                result.order.AddorderRow(rgb.intC1.ToString(), rgb.strC1, rgb.strC2.ToString(), rgb.strC11, rgb.strC3, rgb.strC4, rgb.strC5, rgb.intC3.ToString(), rgb.strC6, rgb.strC7, rgb.strC15, rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC12, rgb.strC14);

            }

            result.datos.AdddatosRow(periodo, totalfee, currency, style, parametro, imagen);
        }
        catch (Exception ex)
        {
            result = null;
            Utility.writeError(ex.Message + ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();
        }




        return result;
    }
    public static REPORTDS getEvalReport(string where, string periodo, string totalfee, string currency, string parametro, string style, Byte[] imagen)
    {


        REPORTDS result = new REPORTDS();
        RE_GenericBean rgb = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        string rxml = null;
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        rxml = service.getCompanies();
        DataSet dscompany = null;

        if (!rxml.Equals("") || rxml != null)
        {
            dscompany = Utility.getCompanies(rxml);
        }
        Utility.setVariablesSession();
        DataSet dsaccount = (DataSet)HttpContext.Current.Session["accounts"];

        DataSet usuarios = (DataSet)HttpContext.Current.Session["Usuarios"];
        DataSet usuVendor = (DataSet)HttpContext.Current.Session["usuVendor"];
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            string fee = "fee";
            string campofail = "orden.ord_failed";

            if (!where.Equals(""))
            {
                where = " WHERE " + where;
                if (parametro.Equals("ord_submitted"))
                {
                    where = where + " and (orden.ord_submitted_done = 'YES' )";
                }

            }

            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT orden.order_id, ordernum, client_id,  company, stnum, stadd, stcity, status_id, case when ord_failed is not null then 'Y' else '' end  AS FAIL, psfprice,   CONVERT(VARCHAR(8),orden." + parametro + ", 1) as date, PRODUCT.initial ,account, case when paid = 'YES' then 'Y' else '' end as paid   FROM [ORDER] orden  INNER JOIN PRODUCT ON orden.product_id = PRODUCT.product_id  " + where + " order by 11,12";

            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//order_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//order_num
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//client_id
                if (!reader.IsDBNull(3)) rgb.intC2 = reader.GetInt32(3);//company 
                if (!reader.IsDBNull(4)) rgb.strC3 = reader.GetString(4);//stnum 
                if (!reader.IsDBNull(5)) rgb.strC4 = reader.GetString(5);//stadd 
                if (!reader.IsDBNull(6)) rgb.strC5 = reader.GetString(6);//stcity
                if (!reader.IsDBNull(7)) rgb.intC3 = reader.GetInt32(7);//status_id
                if (!reader.IsDBNull(8)) rgb.strC6 = reader.GetString(8);//ord_failed
                if (!reader.IsDBNull(9)) rgb.strC7 = reader.GetFloat(9).ToString();//fee 
                if (!reader.IsDBNull(10)) rgb.strC8 = reader.GetString(10).ToString();//ord_date
                if (!reader.IsDBNull(11)) rgb.strC9 = reader.GetString(11).ToString();//ord_type
                if (!reader.IsDBNull(12)) rgb.intC4 = reader.GetInt32(12);//account
                if (!reader.IsDBNull(13)) rgb.strC10 = reader.GetString(13);//paid

                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.intC2.ToString()))
                        {
                            rgb.strC11 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }
                //buscando el account
                if (dsaccount != null)
                {
                    for (int ii = 0; ii <= (dsaccount.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccount.Tables[0].Rows[ii][0].ToString().Equals(rgb.intC4.ToString()))
                        {
                            rgb.strC12 = dsaccount.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }





                //si la orden esta fallada voy a traer el agente, date, failid del fallo 


                result.order.AddorderRow(rgb.intC1.ToString(), rgb.strC1, rgb.strC2.ToString(), rgb.strC11, rgb.strC3, rgb.strC4, rgb.strC5, rgb.intC3.ToString(), rgb.strC6, rgb.strC7, rgb.strC15, rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC12, rgb.strC14);

            }

            result.datos.AdddatosRow(periodo, totalfee, currency, style, parametro, imagen);
        }
        catch (Exception ex)
        {
            result = null;
            Utility.writeError(ex.Message + ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();
        }




        return result;
    }
    public static REPORTDS getDNSReport(string where, string periodo, string totalfee, string currency, string parametro, string style, Byte[] imagen)
    {


        REPORTDS result = new REPORTDS();
        RE_GenericBean rgb = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlCommand comm2 = null;
        SqlDataReader reader2 = null;
        SqlConnection conn = null;
        string rxml = null;
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        rxml = service.getCompanies();
        DataSet dscompany = null;

        if (!rxml.Equals("") || rxml != null)
        {
            dscompany = Utility.getCompanies(rxml);
        }
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;


            comm.CommandType = CommandType.Text;
             string where2="";
             if (!where.Equals(""))
             {
                 where2 = where.Replace("orden.ord_processor", "ord_processor");
                 where2 = where2.Replace("ord_rv_date", "ord_submitted_date");
                 where2 = " Where " + where2;
                 where = " and "+where;
             }
            
            

            comm.CommandText = "SELECT orden.order_id, orden.ordernum, CONVERT(VARCHAR(8), orden.ord_rv_date, 1) AS rv_date, orden.ord_processor, orden.ord_qc, QCSUB.q7, QCSUB.q8,  QCSUB.q9, QCSUB.comment, orden.company, total.Expr1  FROM         [ORDER] AS orden , QCSUB, (SELECT     COUNT(*) AS Expr1, ord_processor FROM  [ORDER]  " + where2 + " GROUP BY ord_processor) as total  WHERE     QCSUB.order_id= orden.order_id and orden.ord_processor = total.ord_processor  " + where + " and ord_rv is not null  order by orden.ord_qc, orden.ord_processor";

            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//order_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//order_num
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//rv_date month
                if (!reader.IsDBNull(3)) rgb.strC3 = reader.GetString(3);//processor
                if (!reader.IsDBNull(4)) rgb.strC4 = reader.GetString(4);//qc
                if (!reader.IsDBNull(5)) rgb.strC5 = reader.GetString(5);//q7 
                if (!reader.IsDBNull(6)) rgb.strC6 = reader.GetString(6);//q8
                if (!reader.IsDBNull(7)) rgb.strC7 = reader.GetString(7);//q9
                if (!reader.IsDBNull(8)) rgb.strC8 = reader.GetString(8);//comments
                if (!reader.IsDBNull(9)) rgb.intC2 = reader.GetInt32(9);//companyid
                if (!reader.IsDBNull(10)) rgb.intC3 = reader.GetInt32(10);// total procesadas


                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.intC2.ToString()))
                        {
                            rgb.strC9 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }




                //si la orden esta fallada voy a traer el agente, date, failid del fallo 


                result.order.AddorderRow(rgb.intC1.ToString(), rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.intC3.ToString(), rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC12, rgb.strC14);

            }

            result.datos.AdddatosRow(periodo, totalfee, currency, style, parametro, imagen);
        }
        catch (Exception ex)
        {
            result = null;
            Utility.writeError(ex.Message + ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();
        }




        return result;
    }


    public static int SavePhoto(string received, string exterioronly, string damages, int orden, string driverextfee)
    {//guarda la info de photos
        int result = 0;
        SqlConnection conn = null;
        SqlCommand commupdate = null;
        SqlDataReader reader = null;
        string oldvalue = "";
        string driverext = "";
        try
        {



            commupdate = new SqlCommand();
            conn = OpenConnection();
            commupdate.Connection = conn;
            commupdate.CommandType = CommandType.Text;
            commupdate.CommandText = "select ord_exterioronly, ord_driver_ext from [order] where order_id = @orden";
            commupdate.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = commupdate.ExecuteReader();
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) oldvalue = reader.GetString(0); // exterior only
                if (!reader.IsDBNull(1)) driverext = reader.GetString(1); // driver_Ext

            }
            commupdate.Parameters.Clear();
            reader.Close();
            reader.Dispose();

            commupdate.CommandText = "update [ORDER] set ord_receivephotos=@rphoto, ord_exterioronly=@ext, damages=@damages, ord_driver_ext_fee=@driverextfee where order_id=@orden";
            commupdate.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            commupdate.Parameters.Add("@rphoto", SqlDbType.VarChar).Value = received;
            commupdate.Parameters.Add("@ext", SqlDbType.VarChar).Value = exterioronly;
            commupdate.Parameters.Add("@damages", SqlDbType.VarChar).Value = damages;
            commupdate.Parameters.Add("@driverextfee", SqlDbType.VarChar).Value = driverextfee;
            commupdate.ExecuteNonQuery();



            result = 1;

            conn.Close();



            commupdate.Parameters.Clear();


            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }

        return result;
    }



    public static int saveFailOrder(string agent, string date, string time, int orden, string campotabla, string done)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand commupdate = null;

        try
        {
            String[] agents = agent.Split('-');
            commupdate = new SqlCommand();
            conn = OpenConnection();
            commupdate.Connection = conn;
            commupdate.CommandType = CommandType.Text;
            commupdate.CommandText = "update [ORDER] set " + campotabla + "=@agent, " + campotabla + "_done=@done, " + campotabla + "_date=getdate()  where order_id=@orden";
            commupdate.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            commupdate.Parameters.Add("@agent", SqlDbType.VarChar).Value = agents[0];

            commupdate.Parameters.Add("@done", SqlDbType.VarChar).Value = done;
            commupdate.ExecuteNonQuery();
            result = 1;

            conn.Close();



            commupdate.Parameters.Clear();


            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }

        return result;
    }

    public static string getLastProc(int orden)
    {//obtiene el ultimo agente q proceso la orden
        string result = "";

        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            ArrayList array = new ArrayList();
            comm.CommandText = "SELECT comp_id, processedby, order_id FROM  comparables WHERE (order_id = @orderid) ORDER BY comp_id ";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                result = "";
                if (!reader.IsDBNull(1)) result = reader.GetString(1);
                array.Add(result);
            }
            reader.Close();
            comm.Parameters.Clear();

            comm.CommandText = "SELECT [ORDER].ord_failed, [ORDER].ord_failed_id, ORDER_FAIL.fail_id, ORDER_FAIL.order_fail_id FROM    [ORDER] INNER JOIN   ORDER_FAIL ON [ORDER].order_id = ORDER_FAIL.order_id AND [ORDER].ord_failed_id = ORDER_FAIL.order_fail_id WHERE        ([ORDER].order_id = @orderid) ";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            string failed = ""; int failtype = 0;
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) failed = reader.GetString(0);
                if (!reader.IsDBNull(2)) failtype = reader.GetInt32(2);
            }
            result = (string)array[0];
            if (failed.ToUpper().Equals("YES"))
            {

                result = (string)array[array.Count - 2];
                string[] temp = result.Split('-');
                result = temp[0];


            }
            else if (failed.ToUpper().Equals("NO"))
            {

                result = (string)array[array.Count - 1];
                string[] temp = result.Split('-');
                result = temp[0];
            }

            conn.Close();
        }
        catch (Exception e)
        {

            Utility.writeError(e.Message);
            result = null;

        }
        return result;
    }

    public static RE_GenericBean getFailedIDS(int orden)
    {// obtiene los ids de los failed
        RE_GenericBean result = new RE_GenericBean();
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select top 1 order_fail_id, fail_id from [ORDER_FAIL] where order_id=@orderid order by 1 desc";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) result.intC1 = reader.GetInt32(0); // order_fail_id
                if (!reader.IsDBNull(1)) result.intC2 = reader.GetInt32(1); // fail_id
            }
            reader.Close();
            comm.Parameters.Clear();

            comm.CommandText = "select  ord_failed  from [ORDER] where order_id=@orden "; //ord_failed
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) result.strC1 = reader.GetString(0);
            }

            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            result = null;
        }
        return result;
    }

    public static RE_GenericBean getProcessDateyTime(int orden, string camFecha, string camHora)
    {//obtiene la hora y la fecha de los campos especificados
        //devuelve valor string de fecha y hora
        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select convert(varchar(10)," + camFecha + ",101), convert(varchar(5)," + camHora + ",114)  from [ORDER] where order_id=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) result.strC1 = reader.GetString(0); // fecha
                if (!reader.IsDBNull(1)) result.strC2 = reader.GetString(1); // hora
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError("No gurado Fecha y hora de Proceso " + e.Message + e.StackTrace);
            return null;
        }
        conn.Close();
        return result;
    }

    public static RE_GenericBean getProcessV1V2STR(int orden, string valor1, string valor2)
    {//obtiene 2 valores especificados
        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select " + valor1 + ",  " + valor2 + "  from [ORDER] where order_id=@orden ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) result.strC1 = reader.GetString(0); // valor1
                if (!reader.IsDBNull(1)) result.strC2 = reader.GetString(1); // valor2
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            return null;
        }
        conn.Close();
        return result;
    }

    public static int SaveProcessV1V2STR(string campo1, string campo2, string valor1, string valor2, int orden)
    {// guarda 2 campos de tipo string
        int result = 0;
        SqlConnection conn = null;
        SqlCommand commupdate = null;

        try
        {
            commupdate = new SqlCommand();
            conn = OpenConnection();
            commupdate.Connection = conn;
            commupdate.CommandType = CommandType.Text;
            commupdate.CommandText = "update [ORDER] set " + campo1 + "= @value1, " + campo2 + "= @value2  where order_id=@orden";
            commupdate.Parameters.Add("@orden", SqlDbType.Int).Value = orden;

            commupdate.Parameters.Add("@value1", SqlDbType.VarChar).Value = valor1;
            commupdate.Parameters.Add("@value2", SqlDbType.VarChar).Value = valor2;
            commupdate.ExecuteNonQuery();
            conn.Close();
            commupdate.Parameters.Clear();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }
        return result;
    }

    public static int saveInfoFail(string tabla, string campostr, string valorstr, string campodate, string valordate, string campotime, string valortime, int fail)
    {// guarda un campo string, fecha, hora
        int result = 0;
        SqlConnection conn = null;
        SqlCommand commupdate = null;

        try
        {
            commupdate = new SqlCommand();
            conn = OpenConnection();
            commupdate.Connection = conn;
            commupdate.CommandType = CommandType.Text;
            commupdate.CommandText = "update [" + tabla + "] set " + campostr + "=@str, " + campodate + "= getdate(), " + campotime + "= @time  where  order_fail_id=@fail_id ";
            commupdate.Parameters.Add("@fail_id", SqlDbType.Int).Value = fail;
            commupdate.Parameters.Add("@str", SqlDbType.VarChar).Value = valorstr;
            commupdate.Parameters.Add("@time", SqlDbType.VarChar).Value = valortime;
            commupdate.ExecuteNonQuery();

            if (!valorstr.ToUpper().Equals("SELECT ONE"))
            {
                commupdate.CommandText = "update [ORDER] set ord_reprocessor=@str where ";

            }

            conn.Close();
            commupdate.Parameters.Clear();
            result = 1;
        }
        catch (Exception e)
        {
            result = 0;
            Utility.writeError(e.Message);
        }
        return result;
    }

    public static RE_GenericBean getInfoFail(int fail_id)
    {//obtiene la info de order_fail
        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select  agent, completed, qc, submitted  from [ORDER_FAIL]  where order_fail_id=@fail_id ";
            comm.Parameters.Add("@fail_id", SqlDbType.Int).Value = fail_id;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) result.strC1 = reader.GetString(0); // agent
                if (!reader.IsDBNull(1)) result.strC2 = reader.GetString(1); // completed
                if (!reader.IsDBNull(2)) result.strC3 = reader.GetString(2); // qc
                if (!reader.IsDBNull(3)) result.strC4 = reader.GetString(3); // submitted
            }
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            return null;
        }
        conn.Close();
        return result;
    }


    public static RE_GenericBean setDriverOnlyExt(int orden)
    {
        RE_GenericBean result = new RE_GenericBean(); ;
        SqlConnection conn = null;
        SqlTransaction transaccion;
        SqlCommand comm = null;
        SqlDataReader reader = null;

        conn = OpenConnection();
        transaccion = conn.BeginTransaction();


        try
        {


            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.Transaction = transaccion;
            comm.CommandText = "select ord_driver from [ORDER] where order_id= @order";
            comm.Parameters.Add("@order", SqlDbType.Int).Value = orden;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result.strC1 = reader.GetString(0); // ord_driver
            }
            comm.Parameters.Clear();
            reader.Close();
            reader.Dispose();
            comm.CommandText = "update [order] set ord_driver_ext= @olddriver, ord_driver= '' where order_id=@order";
            comm.Parameters.Add("@olddriver", SqlDbType.VarChar).Value = result.strC1;
            comm.Parameters.Add("@order", SqlDbType.Int).Value = orden;
            comm.ExecuteNonQuery();
            transaccion.Commit();
            conn.Close();

            result.intC1 = 1;
        }
        catch (Exception e)
        {
            result.intC1 = 0;
            Utility.writeError(e.Message + "/n /t " + e.Message);
            transaccion.Rollback();
        }
        return result;
    }

    public static DataSet getCountiesbySector(int sector)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("county");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("enable");//3
        result.Tables["Tabla"].Columns.Add("initial");//4


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT DISTINCT COUNTY.county_id, COUNTY.name, COUNTY.enable, COUNTY.initial, SECTOR.sector_id FROM  ZIPCODE INNER JOIN  AREA INNER JOIN SECTOR_AREA ON AREA.area_id = SECTOR_AREA.area_id ON ZIPCODE.area_id = AREA.area_id INNER JOIN SECTOR ON SECTOR_AREA.sector_id = SECTOR.sector_id INNER JOIN COUNTY INNER JOIN  CITY ON COUNTY.county_id = CITY.county_id ON ZIPCODE.city = CITY.city_id WHERE        (COUNTY.enable = 1) AND (SECTOR.sector_id = @sector) ORDER BY COUNTY.name";
            comm.Parameters.Add("@sector", SqlDbType.Int).Value = sector;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //county_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2); //enable
                if (!reader.IsDBNull(3)) rgb.strC2 = reader.GetString(3);//initial



                object[] objArr = { rgb.intC1, rgb.strC1, rgb.intC2, rgb.strC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }
    public static RE_GenericBean setPaid(ArrayList array, string userid)
    {

        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlTransaction transaccion;

        conn = DB.OpenConnection();
        transaccion = conn.BeginTransaction();
        SqlCommand comm;

        try
        {


            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaccion;
            comm.CommandType = CommandType.Text;

            foreach (RE_GenericBean rg in array)
            {
                SqlDataReader reader = null;
                int bandera = 0; int statusid = 1; string client_id = "";
                string ordernum = "", check = ""; string stcheckid = ""; int checkid = 0; string issueddate = DateTime.Today.ToShortDateString();
                comm.CommandText = "SELECT     tbl_cheque_orden.cor_order_id, [ORDER].ordernum, [ORDER].check#,  tbl_cheque.chk_reference, convert (varchar,tbl_cheque.chk_date,101),  tbl_cheque.chk_client, [ORDER].status_id, [ORDER].client_id FROM         tbl_cheque_orden INNER JOIN [ORDER] ON tbl_cheque_orden.cor_order_id = [ORDER].order_id INNER JOIN tbl_cheque ON tbl_cheque_orden.cor_chk_id = tbl_cheque.chk_id WHERE     (tbl_cheque_orden.cor_order_id = @orden)";
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                // Utility.writeError("Consulta para pagar orden "+ comm.CommandText);
                reader = comm.ExecuteReader();
                while (reader.Read())
                {
                    if (!reader.IsDBNull(0))
                    {
                        if (!reader.IsDBNull(1)) ordernum = reader.GetString(1); //ordernum
                        if (!reader.IsDBNull(2)) stcheckid = reader.GetString(2);//check
                        if (!reader.IsDBNull(3)) check = " Reference : " + reader.GetString(3);//reference
                        if (!reader.IsDBNull(4)) check += " (" + reader.GetString(4) + ") ";//issued date
                        if (!reader.IsDBNull(5)) { check += " -" + reader.GetString(5) + "- "; issueddate = reader.GetString(5); }//client
                        if (!reader.IsDBNull(6)) statusid = reader.GetInt32(6);//order status_id
                        if (!reader.IsDBNull(7)) client_id = reader.GetString(7);//order client_id

                        bandera = 1;
                    }
                }
                reader.Close();
                comm.Parameters.Clear();



                //sI Bandera=0 es porque no esta la orden asignada a ningun cheque, entonces agrego el reg en tbl_cheque_orden 
                //y escribo el #cheuqe en la orden

                if (bandera == 0)
                {
                    //busco issued date del cheque para ponerselo como fecha de pago a la orden
                    comm.CommandText = "SELECT     convert(varchar,tbl_cheque.chk_date,101) FROM  tbl_cheque WHERE (tbl_cheque.chk_id = @id)";
                    comm.Parameters.Add("@id", SqlDbType.Int).Value = rg.strC3;
                    // Utility.writeError("Consulta para pagar orden "+ comm.CommandText);
                    reader = comm.ExecuteReader();
                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0)) issueddate = reader.GetString(0); //ordernum
                    }
                    reader.Close();
                    comm.Parameters.Clear();

                    //busco el cliente de la orden
                    comm.CommandText = "SELECT   client_id FROM  [order] WHERE (order_id = @id)";
                    comm.Parameters.Add("@id", SqlDbType.Int).Value = rg.strC1;
                    // Utility.writeError("Consulta para pagar orden "+ comm.CommandText);
                    reader = comm.ExecuteReader();
                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0)) client_id = reader.GetString(0).Trim(); //ordernum

                    }
                    reader.Close();
                    comm.Parameters.Clear();


                    Utility.writeError("bANDER = 0 EN SET PAID");
                    comm.CommandText = "insert into tbl_cheque_orden (cor_chk_id, cor_order_id) values (@chk,@orden)";
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                    comm.Parameters.Add("@chk", SqlDbType.Int).Value = rg.strC3;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();


                    //actualizo  info de orden 
                    if (client_id.Equals("PACIFICSTAR"))
                    {

                        comm.CommandText = "update [ORDER] set psfprice=@fee, paid='YES' , paid_date=@date, [ORDER].check#=@chk WHERE order_id=@orden ";
                    }
                    else
                    {
                        comm.CommandText = "update [ORDER] set fee=@fee, paid='YES' , paid_date=@date, [ORDER].check#=@chk WHERE order_id=@orden ";
                    }

                    comm.Parameters.Add("@fee", SqlDbType.VarChar).Value = rg.strC2;
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                    comm.Parameters.Add("@chk", SqlDbType.Int).Value = rg.strC3;
                    comm.Parameters.Add("@date", SqlDbType.VarChar).Value = issueddate;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();

                    if (statusid == 3)
                    {
                        comm.CommandText = "update [ORDER] set status_id=5 WHERE order_id=@orden ";

                        comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                        comm.ExecuteNonQuery();
                        comm.Parameters.Clear();

                    }

                    if (client_id.Equals("PACIFICSTAR"))
                    {
                        comm.CommandText = "update [ORDER] set paid_client='YES', paid_client_date=@date  WHERE order_id=@orden ";
                        comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                        comm.Parameters.Add("@date", SqlDbType.VarChar).Value = issueddate;
                        comm.ExecuteNonQuery();
                        comm.Parameters.Clear();

                    }

                    result.intC1 = 1;




                }
                else
                {
                    result.intC1 = 0;
                    //Utility.writeError("bANDERA = 1 SET PAID " + stcheckid.ToString() + " comparado con " + rg.strC3);
                    if (stcheckid.Equals(rg.strC3))
                    {

                        //actualizo  info de orden 
                        if (client_id.Equals("PACIFICSTAR"))
                        {

                            comm.CommandText = "update [ORDER] set psfprice=@fee, paid='YES'  WHERE order_id=@orden ";
                        }
                        else
                        {
                            comm.CommandText = "update [ORDER] set fee=@fee, paid='YES'  WHERE order_id=@orden ";
                        }

                        //actualizo  info de orden si es el mismno cheque
                        //comm.CommandText = "update [ORDER] set fee=@fee, paid='YES'  WHERE order_id=@orden ";
                        comm.Parameters.Add("@fee", SqlDbType.VarChar).Value = rg.strC2;
                        comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                        comm.ExecuteNonQuery();
                        comm.Parameters.Clear();
                        result.intC1 = 1;
                        result.strC1 += "<br> \n  Order " + ordernum + " updated ";
                    }
                    else
                    {
                        result.strC1 += "<br> \n  Order " + ordernum + " not updated belongs to check " + check;
                    }
                }



            }
            transaccion.Commit();
            conn.Close();
        }
        catch (Exception e)
        {
            result.intC1 = 0;
            Utility.writeError(e.StackTrace + "/n /t " + e.Message);
            transaccion.Rollback();
        }
        finally
        {
            if (conn != null) conn.Close();
        }
        return result;
    }

    public static RE_GenericBean setPaidClient(ArrayList array, string userid)
    {

        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlTransaction transaccion;

        conn = DB.OpenConnection();
        transaccion = conn.BeginTransaction();
        SqlCommand comm;

        try
        {


            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaccion;
            comm.CommandType = CommandType.Text;

            foreach (RE_GenericBean rg in array)
            {
                SqlDataReader reader = null;
                //actualizo  info de orden 
                comm.CommandText = "update [ORDER] set psfprice=@fee, paid_client='YES' , paid_client_date=getdate() WHERE order_id=@orden ";
                comm.Parameters.Add("@fee", SqlDbType.VarChar).Value = rg.strC2;
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                comm.ExecuteNonQuery();
                comm.Parameters.Clear();


                result.intC1 = 1;
            }
            transaccion.Commit();
            conn.Close();
        }
        catch (Exception e)
        {
            result.intC1 = 0;
            Utility.writeError(e.Message + "/n /t " + e.Message);
            transaccion.Rollback();
        }
        finally
        {
            if (conn != null) conn.Close();
        }
        return result;
    }
    public static RE_GenericBean setPaidPaypal(ArrayList array, string userid)
    {

        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlTransaction transaccion;

        conn = DB.OpenConnection();
        transaccion = conn.BeginTransaction();
        SqlCommand comm;

        try
        {


            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaccion;
            comm.CommandType = CommandType.Text;

            foreach (RE_GenericBean rg in array)
            {
                SqlDataReader reader = null;
                int bandera = 0; int statusid = 1;
                string ordernum = "", check = ""; string stcheckid = ""; int checkid = 0;
                comm.CommandText = "SELECT tlb_paytran_order.payord_tranid, [ORDER].ordernum, [ORDER].check#, tbl_paypal_tran.pay_tran_reference, CONVERT(varchar,  tbl_paypal_tran.pay_tran_date, 101) AS Expr1, tbl_paypal_tran.pay_tran_client, [ORDER].status_id FROM tbl_paypal_tran INNER JOIN tlb_paytran_order ON tbl_paypal_tran.pay_tranid = tlb_paytran_order.payord_tranid INNER JOIN [ORDER] ON tlb_paytran_order.payord_order = [ORDER].order_id WHERE     (tlb_paytran_order.payord_order = @orden)";
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;

                reader = comm.ExecuteReader();
                while (reader.Read())
                {
                    if (!reader.IsDBNull(0))
                    {
                        if (!reader.IsDBNull(1)) ordernum = reader.GetString(1); //ordernum
                        if (!reader.IsDBNull(2)) stcheckid = reader.GetString(2);//check
                        if (!reader.IsDBNull(3)) check = " Reference : " + reader.GetString(3);//reference
                        if (!reader.IsDBNull(4)) check += " (" + reader.GetString(4) + ") ";//date
                        if (!reader.IsDBNull(5)) check += " -" + reader.GetString(5) + "- ";//client
                        if (!reader.IsDBNull(6)) statusid = reader.GetInt32(6);//order status_id

                        bandera = 1;
                    }
                }
                reader.Close();
                comm.Parameters.Clear();



                //sI Bandera=0 es porque no esta la orden asignada a ningun cheque, entonces agrego el reg en tbl_cheque_orden 
                //y escribo el #cheuqe en la orden

                if (bandera == 0)
                {
                    comm.CommandText = "insert into tlb_paytran_order (payord_tranid, payord_order) values (@chk,@orden)";
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                    comm.Parameters.Add("@chk", SqlDbType.Int).Value = rg.strC3;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();


                    //actualizo  info de orden 
                    comm.CommandText = "update [ORDER] set fee=@fee, paid='YES' , paid_date=getdate() WHERE order_id=@orden ";
                    comm.Parameters.Add("@fee", SqlDbType.VarChar).Value = rg.strC2;
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();

                    if (statusid == 3)
                    {
                        comm.CommandText = "update [ORDER] set status_id=5 WHERE order_id=@orden ";

                        comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                        comm.ExecuteNonQuery();
                        comm.Parameters.Clear();

                    }

                    result.intC1 = 1;




                }
                else
                {
                    result.intC1 = 0;
                    if (stcheckid.Equals(rg.strC3))
                    {

                        //actualizo  info de orden si es el mismno cheque
                        comm.CommandText = "update [ORDER] set fee=@fee, paid='YES'  WHERE order_id=@orden ";
                        comm.Parameters.Add("@fee", SqlDbType.VarChar).Value = rg.strC2;
                        comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                        comm.ExecuteNonQuery();
                        comm.Parameters.Clear();
                        result.intC1 = 1;
                        result.strC1 += "<br> \n  Order " + ordernum + " updated ";
                    }
                    else
                    {
                        result.strC1 += "<br> \n  Order " + ordernum + " not updated belongs to check " + check;
                    }
                }



            }
            transaccion.Commit();
            conn.Close();
        }
        catch (Exception e)
        {
            result.intC1 = 0;
            Utility.writeError(e.Message + "/n /t " + e.Message);
            transaccion.Rollback();
        }
        finally
        {
            if (conn != null) conn.Close();
        }
        return result;
    }

    public static DataSet getBanks()
    {
        DataSet result = new DataSet();
        result.Tables.Add("Bank");
        result.Tables["Bank"].Columns.Add("id");//1
        result.Tables["Bank"].Columns.Add("name");//2
        result.Tables["Bank"].Columns.Add("type");//3

        result.Tables["Bank"].Columns.Add("image");//4

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "select ban_id, ban_name, ban_type, ban_image from tbl_bancos order by ban_name";

            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //bank id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2); //type
                if (!reader.IsDBNull(3)) rgb.strC2 = reader.GetString(3); //image




                object[] objArr = { rgb.intC1, rgb.strC1, rgb.intC2, rgb.strC2 };
                result.Tables["Bank"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }

    public static RE_GenericBean getBanco(int id)
    {


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        RE_GenericBean rgb = new RE_GenericBean();
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "select ban_id, ban_name, ban_type,  ban_image, ban_number from tbl_bancos where ban_id=@bank ";
            comm.Parameters.Add("@bank", SqlDbType.Int).Value = id;

            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //bank id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2); //type
                if (!reader.IsDBNull(3)) rgb.strC2 = reader.GetString(3); //image
                if (!reader.IsDBNull(4)) rgb.strC3 = reader.GetString(4); //number




            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return rgb;
    }


    public static int addBank(string name, int id, string type, string image, string number)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;

        RE_GenericBean rgb = new RE_GenericBean();
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (id == 0)
            {// si es nuevo agrego
                comm.CommandText = " insert into tbl_bancos ( ban_name, ban_type, ban_number) values (@name,@type, @number) ";
                comm.Parameters.Add("@name", SqlDbType.VarChar).Value = name;
                comm.Parameters.Add("@type", SqlDbType.Int).Value = type;
                comm.Parameters.Add("@number", SqlDbType.VarChar).Value = number;


                comm.ExecuteNonQuery();

                comm.Parameters.Clear();
                comm.CommandText = "select max(ban_id) from tbl_bancos ";
                reader = comm.ExecuteReader();
                while (reader.Read())
                {

                    if (!reader.IsDBNull(0)) result = reader.GetInt32(0); //chkid
                }

                reader.Close();
                comm.Parameters.Clear();
                comm.CommandText = "update  tbl_bancos set ban_image=@image where ban_id=@id";
                comm.Parameters.Add("@image", SqlDbType.VarChar).Value = "bankIcon" + result.ToString() + "." + image;
                comm.Parameters.Add("@id", SqlDbType.Int).Value = result;
                comm.ExecuteNonQuery();
            }
            else
            {

                comm.CommandText = " update tbl_bancos set  ban_name=@name, ban_type=@type, ban_number=@number  where ban_id=@bank ";
                comm.Parameters.Add("@name", SqlDbType.VarChar).Value = name;
                comm.Parameters.Add("@type", SqlDbType.Int).Value = type;
                comm.Parameters.Add("@bank", SqlDbType.Int).Value = id;
                comm.Parameters.Add("@number", SqlDbType.VarChar).Value = number;

                comm.ExecuteNonQuery();
                comm.Parameters.Clear();

                if (!image.Equals(""))
                {
                    comm.CommandText = "update  tbl_bancos set ban_image=@image where ban_id=@id";
                    comm.Parameters.Add("@image", SqlDbType.VarChar).Value = "bankIcon" + id + "." + image;
                    comm.Parameters.Add("@id", SqlDbType.Int).Value = id;
                    comm.ExecuteNonQuery();
                }


                result = id;
            }



            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = 0;
        }
        return result;
    }

    public static int deleteBank(int id)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;


        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (id != 0)
            {// si es nuevo agrego
                comm.CommandText = " delete from  tbl_bancos where ban_id=@bank ";
                comm.Parameters.Add("@bank", SqlDbType.Int).Value = id;

                comm.ExecuteNonQuery();

                result = 1;
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = 0;
        }
        return result;
    }

    public static int addDeposit(RE_GenericBean rg, int dep)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;


        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (dep == 0)
            {// si es nuevo agrego
                comm.CommandText = " insert into tbl_deposito ( dep_bank_id, dep_reference, dep_date, dep_amount) values (@bank,@ref,@date,@ammo) ";
                comm.Parameters.Add("@bank", SqlDbType.Int).Value = rg.intC1;
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1;
                comm.Parameters.Add("@date", SqlDbType.Date).Value = rg.strC2;
                comm.Parameters.Add("@ammo", SqlDbType.Money).Value = rg.strC3;
                comm.ExecuteNonQuery();

                comm.CommandText = " select max(dep_id) from tbl_deposito ";
                comm.Parameters.Clear();
                reader = comm.ExecuteReader();

                while (reader.Read())
                {
                    if (!reader.IsDBNull(0)) result = reader.GetInt32(0); //chkid
                }
                reader.Close();

            }
            else
            {
                comm.CommandText = " update tbl_deposito set  dep_bank_id=@bank, dep_date=@date , dep_amount=@ammo, dep_reference=@ref where dep_id=@depid ";
                comm.Parameters.Add("@bank", SqlDbType.Int).Value = rg.intC1;
                comm.Parameters.Add("@date", SqlDbType.Date).Value = rg.strC2;
                comm.Parameters.Add("@ammo", SqlDbType.Money).Value = rg.strC3;
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1;
                comm.Parameters.Add("@depid", SqlDbType.Int).Value = dep;
                comm.ExecuteNonQuery();
                result = dep;
            }



            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = 0;
        }
        return result;

    }
    public static int addDepositPaypal(RE_GenericBean rg, int dep)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;


        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (dep == 0)
            {// si es nuevo agrego
                comm.CommandText = " insert into tbl_dep_pay (dep_pay_reference, dep_pay_date) values (@ref,@date) ";
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1;
                comm.Parameters.Add("@date", SqlDbType.Date).Value = rg.strC2;
                //comm.Parameters.Add("@ammo", SqlDbType.Money).Value = rg.strC3;
                comm.ExecuteNonQuery();

                comm.CommandText = " select max(dep_pay_id) from tbl_dep_pay ";
                comm.Parameters.Clear();
                reader = comm.ExecuteReader();

                while (reader.Read())
                {
                    if (!reader.IsDBNull(0)) result = reader.GetInt32(0); //deppayid
                }
                reader.Close();

            }
            else
            {
                comm.CommandText = " update tbl_dep_pay set  dep_pay_date=@date ,  dep_pay_reference=@ref where dep_id=@depid ";
                comm.Parameters.Add("@date", SqlDbType.Date).Value = rg.strC2;
                // comm.Parameters.Add("@ammo", SqlDbType.Money).Value = rg.strC3;
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1;
                comm.Parameters.Add("@depid", SqlDbType.Int).Value = dep;
                comm.ExecuteNonQuery();
                result = dep;
            }



            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = 0;
        }
        return result;

    }

    public static int deleteDeposit(int dep)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;


        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (dep != 0)
            {// si es nuevo agrego
                comm.CommandText = " delete from  tbl_deposito where dep_id=@depid ";
                comm.Parameters.Add("@depid", SqlDbType.Int).Value = dep;

                comm.ExecuteNonQuery();

                result = 1;
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = 0;
        }
        return result;
    }

    public static DataSet getDeposits(int type, ArrayList criteriobusqueda)
    {// type=1 -->Anios, type=2--> Mes , type=3 -->cheques
        DataSet result = new DataSet();
        result.Tables.Add("Deposit");
        result.Tables["Deposit"].Columns.Add("id");//1
        result.Tables["Deposit"].Columns.Add("name");//2
        result.Tables["Deposit"].Columns.Add("type");//3
        result.Tables["Deposit"].Columns.Add("ammount");//4
        result.Tables["Deposit"].Columns.Add("campo2");//4
        result.Tables["Deposit"].Columns.Add("campo3");//4

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (type == 1)
            {//si es por anio
                comm.CommandText = " SELECT DISTINCT CONVERT(VARCHAR(10), YEAR(dep_date)) AS Expr1 FROM    tbl_deposito  order by 1 desc";

                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //bank id
                    if (!reader.IsDBNull(0)) rgb.strC2 = reader.GetString(0);//name
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC4, rgb.strC4 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }

            }
            else if (type == 2)
            {

                comm.CommandText = "SELECT  year,  M, mesint FROM  (SELECT DISTINCT CONVERT(VARCHAR(10), YEAR(dep_date)) AS year, DATENAME(MONTH, dep_date) AS M  , MONTH(dep_date) as mesint FROM  tbl_deposito) AS tabla WHERE   (year = @year) ORDER BY  mesint";
                comm.Parameters.Add("@year", SqlDbType.VarChar).Value = criteriobusqueda[0];
                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //year
                    if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//month string
                    if (!reader.IsDBNull(2)) rgb.intC1 = reader.GetInt32(2);//month string
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.intC1, rgb.strC3, rgb.strC4, rgb.strC4 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }

            }
            else if (type == 3)
            {
                comm.CommandText = "SELECT  tabla.dep_id, tbl_bancos.ban_name, tabla.dep_reference, tabla.amount,  conteo.orders, tbl_bancos.ban_number FROM  (SELECT     tbl_cheque.chk_dep_id, COUNT(tbl_cheque_orden.cor_order_id) AS orders FROM tbl_cheque_orden INNER JOIN tbl_cheque ON tbl_cheque_orden.cor_chk_id = tbl_cheque.chk_id GROUP BY tbl_cheque.chk_dep_id) AS conteo RIGHT OUTER JOIN (SELECT     dep_id, dep_bank_id, dep_reference, CONVERT(varchar(10), dep_amount) AS amount, MONTH(dep_date) AS mes, YEAR(dep_date)  AS anio FROM tbl_deposito) AS tabla INNER JOIN tbl_bancos ON tabla.dep_bank_id = tbl_bancos.ban_id ON conteo.chk_dep_id = tabla.dep_id WHERE     (tabla.mes = @month) AND (tabla.anio = @year)";
                comm.Parameters.Add("@year", SqlDbType.VarChar).Value = criteriobusqueda[0];
                comm.Parameters.Add("@month", SqlDbType.VarChar).Value = criteriobusqueda[1];
                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetInt32(0).ToString(); //dep_id
                    if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//bank
                    if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2);//dep_reference
                    if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3);//dep_amount
                    if (!reader.IsDBNull(4)) rgb.strC5 = reader.GetInt32(4).ToString();//#orders by deposit
                    if (!reader.IsDBNull(5)) rgb.strC6 = reader.GetString(5); //ban number
                    if (rgb.strC5 == "") { rgb.strC5 = "0"; }
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }


            }
            else if (type == 4)
            {
                comm.CommandText = "SELECT tbl_deposito.dep_id, tbl_bancos.ban_id, tbl_bancos.ban_name, tbl_deposito.dep_reference, convert(varchar(10),tbl_deposito.dep_date) as date, convert( varchar(10), tbl_deposito.dep_amount) FROM  tbl_deposito INNER JOIN  tbl_bancos ON tbl_deposito.dep_bank_id = tbl_bancos.ban_id WHERE   (tbl_deposito.dep_id = @depid )";
                comm.Parameters.Add("@depid", SqlDbType.VarChar).Value = criteriobusqueda[0];

                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetInt32(0).ToString(); //dep_id
                    if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetInt32(1).ToString();//bank id
                    if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2);//bank name
                    if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3).ToString();//dep_reference
                    if (!reader.IsDBNull(4)) rgb.strC5 = reader.GetString(4);//dep_date
                    if (!reader.IsDBNull(5)) rgb.strC6 = reader.GetString(5);//dep_ammount
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }
            }
            else if (type == 5)
            {
                comm.CommandText = "SELECT  dep_id, tbl_bancos.ban_name, dep_reference, convert ( varchar(10),dep_amount) as amount, convert (varchar(10),dep_date, 101  )  as date FROM    tbl_deposito, tbl_bancos where tbl_bancos.ban_id = tbl_deposito.dep_bank_id ";
                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetInt32(0).ToString(); //dep_id
                    if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//bank id
                    if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2);//dep_reference
                    if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3);//dep_amount
                    if (!reader.IsDBNull(4)) rgb.strC5 = reader.GetString(4);//dep_date
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }


            }


            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }

    public static DataSet getDepositsPay(int type, ArrayList criteriobusqueda)
    {// type=1 -->Anios, type=2--> Mes , type=3 -->cheques
        DataSet result = new DataSet();
        result.Tables.Add("Deposit");
        result.Tables["Deposit"].Columns.Add("id");//1
        result.Tables["Deposit"].Columns.Add("name");//2
        result.Tables["Deposit"].Columns.Add("type");//3
        result.Tables["Deposit"].Columns.Add("ammount");//4
        result.Tables["Deposit"].Columns.Add("campo2");//4
        result.Tables["Deposit"].Columns.Add("campo3");//4

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (type == 1)
            {//si es por anio
                comm.CommandText = " SELECT DISTINCT CONVERT(VARCHAR(10), YEAR(dep_pay_date)) AS Expr1 FROM    tbl_dep_pay  order by 1 desc";

                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //bank id
                    if (!reader.IsDBNull(0)) rgb.strC2 = reader.GetString(0);//name
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC4, rgb.strC4 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }

            }
            else if (type == 2)
            {

                comm.CommandText = "SELECT  year,  M, mesint FROM  (SELECT DISTINCT CONVERT(VARCHAR(10), YEAR(dep_pay_date)) AS year, DATENAME(MONTH, dep_pay_date) AS M  , MONTH(dep_pay_date) as mesint FROM  tbl_dep_pay) AS tabla WHERE   (year = @year) ORDER BY  mesint";
                comm.Parameters.Add("@year", SqlDbType.VarChar).Value = criteriobusqueda[0];
                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //year
                    if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//month string
                    if (!reader.IsDBNull(2)) rgb.intC1 = reader.GetInt32(2);//month string
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.intC1, rgb.strC3, rgb.strC4, rgb.strC4 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }

            }
            else if (type == 3)
            {
                comm.CommandText = "SELECT  dep_pay_id, 'Paypal' AS Bank, dep_pay_reference, amount, co FROM  (SELECT     tbl_dep_pay.dep_pay_id, tbl_dep_pay.dep_pay_reference, convert(varchar,SUM(tbl_paypal_tran_1.pay_tran_amount)) AS amount, MONTH(tbl_dep_pay.dep_pay_date) AS mes, YEAR(tbl_dep_pay.dep_pay_date) AS anio, COUNT(tbl_paypal_tran_1.pay_tran_amount)  AS co FROM tbl_dep_pay INNER JOIN tbl_paypal_tran AS tbl_paypal_tran_1 ON tbl_dep_pay.dep_pay_id = tbl_paypal_tran_1.pay_deppay_id  GROUP BY tbl_dep_pay.dep_pay_id, tbl_dep_pay.dep_pay_reference, tbl_dep_pay.dep_pay_date) AS tabla WHERE     (mes = @month) AND (anio = @year)";
                comm.Parameters.Add("@year", SqlDbType.VarChar).Value = criteriobusqueda[0];
                comm.Parameters.Add("@month", SqlDbType.VarChar).Value = criteriobusqueda[1];
                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetInt32(0).ToString(); //dep_id
                    if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//bank
                    if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2);//dep_reference
                    if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3);//dep_amount
                    if (!reader.IsDBNull(4)) rgb.strC5 = reader.GetInt32(4).ToString();//#orders by dep
                    rgb.strC6 = "0"; //ban number
                    if (rgb.strC5 == "") { rgb.strC5 = "0"; }
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }


            }
            else if (type == 4)
            {
                comm.CommandText = "SELECT     dep_pay_id,0,'Paypal',dep_pay_reference, CONVERT(varchar(10), dep_pay_date) AS date, CONVERT(varchar(10), dep_pay_amount) AS Expr1 FROM tbl_dep_pay WHERE     (dep_pay_id = @depid)";
                comm.Parameters.Add("@depid", SqlDbType.VarChar).Value = criteriobusqueda[0];

                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetInt32(0).ToString(); //dep_id
                    if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetInt32(1).ToString();//bank id
                    if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2);//bank name
                    if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3).ToString();//dep_reference
                    if (!reader.IsDBNull(4)) rgb.strC5 = reader.GetString(4);//dep_date
                    if (!reader.IsDBNull(5)) rgb.strC6 = reader.GetString(5);//dep_ammount
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }
            }
            else if (type == 5)
            {
                comm.CommandText = "SELECT dep_pay_id, dep_pay_reference, CONVERT(varchar(10), dep_pay_amount) AS amount, CONVERT(varchar(10), dep_pay_date, 101) AS date FROM  tbl_dep_pay";
                reader = comm.ExecuteReader();
                RE_GenericBean rgb = null;
                while (reader.Read())
                {
                    rgb = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetInt32(0).ToString(); //dep_id
                    if (!reader.IsDBNull(1)) rgb.strC2 = reader.GetString(1);//bank id
                    if (!reader.IsDBNull(2)) rgb.strC3 = reader.GetString(2);//dep_reference
                    if (!reader.IsDBNull(3)) rgb.strC4 = reader.GetString(3);//dep_amount
                    if (!reader.IsDBNull(4)) rgb.strC5 = reader.GetString(4);//dep_date
                    object[] objArr = { rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6 };
                    result.Tables["Deposit"].Rows.Add(objArr);
                }


            }


            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }

    public static DataSet GetOrdersbyCheck(string p)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Order #");//0
        result.Tables["Tabla"].Columns.Add("Status");// 1status order
        result.Tables["Tabla"].Columns.Add("Client");//2
        result.Tables["Tabla"].Columns.Add("Company");//3
        result.Tables["Tabla"].Columns.Add("Account");//4
        result.Tables["Tabla"].Columns.Add("Type");//5
        result.Tables["Tabla"].Columns.Add("Street");//6
        result.Tables["Tabla"].Columns.Add("Street Address");//7
        result.Tables["Tabla"].Columns.Add("Zip");//8
        result.Tables["Tabla"].Columns.Add("orderid");//9 yes or no
        result.Tables["Tabla"].Columns.Add("fee");//10 ord_failed_id
        result.Tables["Tabla"].Columns.Add("psffee");//11 yes o no
        result.Tables["Tabla"].Columns.Add("Paid");// 12status order
        result.Tables["Tabla"].Columns.Add("PaidDate");// 13status order
        result.Tables["Tabla"].Columns.Add("sum");// 14sumatoria acumulada fee
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT  [ORDER].ordernum, STATUS.name, [ORDER].client_id, [ORDER].company, [ORDER].account, PRODUCT.initial, [ORDER].stnum, [ORDER].stadd, [ORDER].zip,  [ORDER].order_id, convert(varchar(10),[ORDER].fee), convert(varchar(10), [ORDER].psfprice), [ORDER].paid, convert(varchar(10),[ORDER].paid_date,101) FROM  tbl_cheque_orden INNER JOIN  [ORDER] ON tbl_cheque_orden.cor_order_id = [ORDER].order_id INNER JOIN PRODUCT ON [ORDER].product_id = PRODUCT.product_id INNER JOIN STATUS ON [ORDER].status_id = STATUS.status_id WHERE        (tbl_cheque_orden.cor_chk_id = @chk) ";
            comm.Parameters.Add("@chk", SqlDbType.Int).Value = p;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            double sum = 0;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //orden#
                if (!reader.IsDBNull(1)) rgb.strC3 = reader.GetString(1).ToString();//status name
                if (!reader.IsDBNull(2)) rgb.strC4 = reader.GetString(2);//client
                if (!reader.IsDBNull(3)) rgb.strC5 = reader.GetInt32(3).ToString();//company
                if (!reader.IsDBNull(4)) rgb.strC6 = reader.GetInt32(4).ToString();//account
                if (!reader.IsDBNull(5)) rgb.strC7 = reader.GetString(5);//product name
                if (!reader.IsDBNull(6)) rgb.strC8 = reader.GetString(6);//st num
                if (!reader.IsDBNull(7)) rgb.strC9 = reader.GetString(7);//st address
                if (!reader.IsDBNull(8)) rgb.strC10 = reader.GetString(8);//zip
                if (!reader.IsDBNull(9)) rgb.intC1 = reader.GetInt32(9);//company
                if (!reader.IsDBNull(10)) rgb.strC11 = reader.GetString(10).ToString(); //fee
                if (!reader.IsDBNull(11)) rgb.strC12 = reader.GetString(11);  //psfprice
                if (!reader.IsDBNull(12)) rgb.strC13 = reader.GetString(12);  //paid
                if (!reader.IsDBNull(13)) rgb.strC14 = reader.GetString(13);  //paid date
                double temp = double.Parse(rgb.strC11);

                if (rgb.strC4 == "PACIFICSTAR") { rgb.strC11 = rgb.strC12; temp = double.Parse(rgb.strC12); }
                sum = sum + temp;
                rgb.strC15 = sum.ToString();
                Utility.setVariablesSession();
                DataSet dscompany = (DataSet)HttpContext.Current.Session["companies"];
                DataSet dsaccounts = (DataSet)HttpContext.Current.Session["accounts"];
                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC5.ToString()))
                        {
                            rgb.strC5 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                if (dsaccounts != null)
                {
                    for (int ii = 0; ii <= (dsaccounts.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccounts.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC6.ToString()))
                        {
                            rgb.strC6 = dsaccounts.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                object[] objArr = { rgb.strC1, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.intC1, rgb.strC11, rgb.strC12, rgb.strC13, rgb.strC14, rgb.strC15 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace + e.Message);
            return null;
        }
        return result;
    }

    public static DataSet GetOrdersbyTrans(string p)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Order #");//0
        result.Tables["Tabla"].Columns.Add("Status");// 2status order
        result.Tables["Tabla"].Columns.Add("Client");//3
        result.Tables["Tabla"].Columns.Add("Company");//4
        result.Tables["Tabla"].Columns.Add("Account");//5
        result.Tables["Tabla"].Columns.Add("Type");//5
        result.Tables["Tabla"].Columns.Add("Street");//6
        result.Tables["Tabla"].Columns.Add("Street Address");//7
        result.Tables["Tabla"].Columns.Add("Zip");//8
        result.Tables["Tabla"].Columns.Add("orderid");//9 yes or no
        result.Tables["Tabla"].Columns.Add("fee");//10 ord_failed_id
        result.Tables["Tabla"].Columns.Add("psffee");//11 yes o no
        result.Tables["Tabla"].Columns.Add("Paid");// 1status order
        result.Tables["Tabla"].Columns.Add("PaidDate");// 1status order
        result.Tables["Tabla"].Columns.Add("sum");// sumatoria acumulada fee
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT     [ORDER].ordernum, STATUS.name, [ORDER].client_id, [ORDER].company, [ORDER].account, PRODUCT.initial, [ORDER].stnum, [ORDER].stadd, [ORDER].zip, [ORDER].order_id, CONVERT(varchar(10), [ORDER].fee) AS Expr1, CONVERT(varchar(10), [ORDER].psfprice) AS Expr2, [ORDER].paid, CONVERT(varchar(10), [ORDER].paid_date, 101) AS Expr3 FROM  [ORDER] INNER JOIN  PRODUCT ON [ORDER].product_id = PRODUCT.product_id INNER JOIN  STATUS ON [ORDER].status_id = STATUS.status_id INNER JOIN  tlb_paytran_order ON [ORDER].order_id = tlb_paytran_order.payord_order WHERE     (tlb_paytran_order.payord_tranid = @tran)";
            comm.Parameters.Add("@tran", SqlDbType.Int).Value = p;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            double sum = 0;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //orden#
                if (!reader.IsDBNull(1)) rgb.strC3 = reader.GetString(1).ToString();//status name
                if (!reader.IsDBNull(2)) rgb.strC4 = reader.GetString(2);//client
                if (!reader.IsDBNull(3)) rgb.strC5 = reader.GetInt32(3).ToString();//company
                if (!reader.IsDBNull(4)) rgb.strC6 = reader.GetInt32(4).ToString();//account
                if (!reader.IsDBNull(5)) rgb.strC7 = reader.GetString(5);//product name
                if (!reader.IsDBNull(6)) rgb.strC8 = reader.GetString(6);//st num
                if (!reader.IsDBNull(7)) rgb.strC9 = reader.GetString(7);//st address
                if (!reader.IsDBNull(8)) rgb.strC10 = reader.GetString(8);//zip
                if (!reader.IsDBNull(9)) rgb.intC1 = reader.GetInt32(9);//company
                if (!reader.IsDBNull(10)) rgb.strC11 = reader.GetString(10).ToString(); //fee
                if (!reader.IsDBNull(11)) rgb.strC12 = reader.GetString(11);  //psfprice
                if (!reader.IsDBNull(12)) rgb.strC13 = reader.GetString(12);  //paid
                if (!reader.IsDBNull(13)) rgb.strC14 = reader.GetString(13);  //paid date
                double temp = double.Parse(rgb.strC11);
                sum = sum + temp;
                rgb.strC15 = sum.ToString();

                Utility.setVariablesSession();
                DataSet dscompany = (DataSet)HttpContext.Current.Session["companies"];
                DataSet dsaccounts = (DataSet)HttpContext.Current.Session["accounts"];
                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC5.ToString()))
                        {
                            rgb.strC5 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                if (dsaccounts != null)
                {
                    for (int ii = 0; ii <= (dsaccounts.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccounts.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC6.ToString()))
                        {
                            rgb.strC6 = dsaccounts.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                object[] objArr = { rgb.strC1, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.intC1, rgb.strC11, rgb.strC12, rgb.strC13, rgb.strC14, rgb.strC15 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace + e.Message);
            return null;
        }
        return result;
    }

    public static DataSet GetCheckbyDep(string p)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("chkid");//0
        result.Tables["Tabla"].Columns.Add("bankid");// 2status order
        result.Tables["Tabla"].Columns.Add("reference");//3
        result.Tables["Tabla"].Columns.Add("date");//4
        result.Tables["Tabla"].Columns.Add("amount");//5
        result.Tables["Tabla"].Columns.Add("client");//5
        result.Tables["Tabla"].Columns.Add("company");//7
        result.Tables["Tabla"].Columns.Add("account");//8
        result.Tables["Tabla"].Columns.Add("dateproc");//9 yes or no
        result.Tables["Tabla"].Columns.Add("sum");//9 yes or no

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT  tbl_cheque.chk_id, tbl_bancos.ban_name, tbl_cheque.chk_reference, convert( varchar(10), tbl_cheque.chk_amount) amount, tbl_cheque.chk_client, tbl_cheque.chk_company, tbl_cheque.chk_account, convert( varchar(10), tbl_cheque.chk_date,101) date, convert( varchar(10),tbl_cheque.chk_date_process,101) dateproc FROM            tbl_deposito INNER JOIN    tbl_cheque ON tbl_deposito.dep_id = tbl_cheque.chk_dep_id INNER JOIN  tbl_bancos ON tbl_cheque.chk_bank_id = tbl_bancos.ban_id WHERE        (tbl_deposito.dep_id = @dep)";
            comm.Parameters.Add("@dep", SqlDbType.Int).Value = p;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            double sum = 0;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //chkid
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//banckid
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//reference
                if (!reader.IsDBNull(3)) rgb.strC3 = reader.GetString(3);//chkamount
                if (!reader.IsDBNull(4)) rgb.strC4 = reader.GetString(4);//client
                if (!reader.IsDBNull(5)) rgb.intC2 = reader.GetInt32(5);//coompany
                if (!reader.IsDBNull(6)) rgb.intC3 = reader.GetInt32(6);//acc
                if (!reader.IsDBNull(7)) rgb.strC7 = reader.GetString(7);//date
                if (!reader.IsDBNull(8)) rgb.strC8 = reader.GetString(8);//dateproc
                double temp = double.Parse(rgb.strC3);


                sum = sum + temp;
                Utility.setVariablesSession();
                DataSet dscompany = (DataSet)HttpContext.Current.Session["companies"];
                DataSet dsaccounts = (DataSet)HttpContext.Current.Session["accounts"];
                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.intC2.ToString()))
                        {
                            rgb.strC9 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                if (dsaccounts != null)
                {
                    for (int ii = 0; ii <= (dsaccounts.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccounts.Tables[0].Rows[ii][0].ToString().Equals(rgb.intC3.ToString()))
                        {
                            rgb.strC10 = dsaccounts.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }



                object[] objArr = { rgb.intC1, rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC9, rgb.strC10, rgb.strC7, rgb.strC8, sum };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace + e.Message);
            return null;
        }
        return result;
    }

    public static DataSet GetTranbyDep(string p)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("chkid");//0
        result.Tables["Tabla"].Columns.Add("Bank");// 2status order
        result.Tables["Tabla"].Columns.Add("Client");//3
        result.Tables["Tabla"].Columns.Add("Reference");//4
        result.Tables["Tabla"].Columns.Add("Receipt");//5
        result.Tables["Tabla"].Columns.Add("Amount");//5
        result.Tables["Tabla"].Columns.Add("Date");//7
        result.Tables["Tabla"].Columns.Add("Date Processed");//8

        result.Tables["Tabla"].Columns.Add("sum");//9 yes or no

        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT     tbl_paypal_tran.pay_tranid,'Paypal',  tbl_paypal_tran.pay_tran_client, tbl_paypal_tran.pay_tran_reference, tbl_paypal_tran.pay_tran_receipt,convert(varchar,tbl_paypal_tran.pay_tran_amount), convert(varchar, tbl_paypal_tran.pay_tran_date,101), convert(varchar,tbl_paypal_tran.pay_trandate_process,101) FROM tbl_paypal_tran INNER JOIN tbl_dep_pay ON tbl_paypal_tran.pay_deppay_id = tbl_dep_pay.dep_pay_id where tbl_paypal_tran.pay_deppay_id=@dep";
            comm.Parameters.Add("@dep", SqlDbType.Int).Value = p;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            double sum = 0;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.int64C1 = reader.GetInt64(0); //tranid
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//Paypal
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//client
                if (!reader.IsDBNull(3)) rgb.strC3 = reader.GetString(3);//reference
                if (!reader.IsDBNull(4)) rgb.strC4 = reader.GetString(4);//recepeit
                if (!reader.IsDBNull(5)) rgb.strC5 = reader.GetString(5);//amount
                if (!reader.IsDBNull(6)) rgb.strC6 = reader.GetString(6);//date
                if (!reader.IsDBNull(7)) rgb.strC7 = reader.GetString(7);//dateproc
                double temp = double.Parse(rgb.strC5);


                sum = sum + temp;



                object[] objArr = { rgb.int64C1, rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, sum };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace + e.Message);
            return null;
        }
        return result;
    }

    public static RE_GenericBean GetCheckbyID(string p)
    {
        RE_GenericBean result = new RE_GenericBean();


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT  tbl_cheque.chk_id, tbl_bancos.ban_id, tbl_cheque.chk_reference, convert( varchar(10), tbl_cheque.chk_amount) amount, tbl_cheque.chk_client, tbl_cheque.chk_company, tbl_cheque.chk_account, convert( varchar(10), tbl_cheque.chk_date,101) date, convert( varchar(10),tbl_cheque.chk_date_process,101) dateproc, tbl_cheque.chk_dep_id FROM            tbl_deposito INNER JOIN    tbl_cheque ON tbl_deposito.dep_id = tbl_cheque.chk_dep_id INNER JOIN  tbl_bancos ON tbl_cheque.chk_bank_id = tbl_bancos.ban_id WHERE        (tbl_cheque.chk_id = @id)";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = p;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //chkid
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetInt32(1).ToString();//banckid
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//reference
                if (!reader.IsDBNull(3)) rgb.strC3 = reader.GetString(3);//amount
                if (!reader.IsDBNull(4)) rgb.strC4 = reader.GetString(4);//client
                if (!reader.IsDBNull(5)) rgb.strC5 = reader.GetInt32(5).ToString();//company
                if (!reader.IsDBNull(6)) rgb.strC6 = reader.GetInt32(6).ToString();//account
                if (!reader.IsDBNull(7)) rgb.strC7 = reader.GetString(7);//date
                if (!reader.IsDBNull(8)) rgb.strC8 = reader.GetString(8);//dateroc
                if (!reader.IsDBNull(9)) rgb.intC2 = reader.GetInt32(9);// depid




                result = rgb;
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }
    public static RE_GenericBean GetTransbyID(string p)
    {
        RE_GenericBean result = new RE_GenericBean();


        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT tbl_paypal_tran.pay_tranid,0, tbl_paypal_tran.pay_tran_reference, convert(varchar, tbl_paypal_tran.pay_tran_amount),  convert( varchar,tbl_paypal_tran.pay_tran_date,101), convert(varchar, tbl_paypal_tran.pay_trandate_process,101), tbl_dep_pay.dep_pay_id, tbl_paypal_tran.pay_tran_client, tbl_paypal_tran.pay_tran_receipt FROM tbl_paypal_tran INNER JOIN tbl_dep_pay ON tbl_paypal_tran.pay_deppay_id = tbl_dep_pay.dep_pay_id WHERE (tbl_paypal_tran.pay_tranid = @id)";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = p;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.int64C1 = reader.GetInt64(0); //chkid
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetInt32(1).ToString();//banckid
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//reference
                if (!reader.IsDBNull(3)) rgb.strC3 = reader.GetString(3);//amount

                if (!reader.IsDBNull(4)) rgb.strC7 = reader.GetString(4);//date
                if (!reader.IsDBNull(5)) rgb.strC8 = reader.GetString(5);//dateroc
                if (!reader.IsDBNull(6)) rgb.intC2 = reader.GetInt32(6);// depid
                if (!reader.IsDBNull(7)) rgb.strC4 = reader.GetString(7);// client
                if (!reader.IsDBNull(8)) rgb.strC5 = reader.GetString(8);// recepeit




                result = rgb;
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            return null;
        }
        return result;
    }

    public static int saveDeposit(int id, RE_GenericBean rg)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;


        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (id == 0)
            {// si es nuevo agrego
                comm.CommandText = " insert into tbl_de ( dep_bank_id, dep_reference, dep_date, dep_amount) values (@bank,@ref,@date,@ammo) ";
                comm.Parameters.Add("@bank", SqlDbType.Int).Value = rg.intC1;
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1;
                comm.Parameters.Add("@date", SqlDbType.Date).Value = rg.strC2;
                comm.Parameters.Add("@ammo", SqlDbType.Money).Value = rg.strC3;

            }
            else
            {
                comm.CommandText = " update tbl_deposito set  dep_bank_id=@bank, dep_date=@date , dep_amount=@ammo, dep_reference=@reg where dep_id=@depid ";
                comm.Parameters.Add("@bank", SqlDbType.Int).Value = rg.intC1;
                comm.Parameters.Add("@date", SqlDbType.Date).Value = rg.strC2;
                comm.Parameters.Add("@ammo", SqlDbType.Money).Value = rg.strC3;
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1;
                comm.Parameters.Add("@depid", SqlDbType.Int).Value = id;
            }
            comm.ExecuteNonQuery();

            result = 1;
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = 0;
        }
        return result;
    }

    public static int addCheck(int dep, RE_GenericBean rg)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;


        RE_GenericBean rgb = new RE_GenericBean();
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            if (rg.intC1 == 0)
            {// si es nuevo agrego
                int chkid = 0;
                //pero primero verifico que no exista en el sistema
                comm.CommandText = "select chk_id  from tbl_cheque where chk_bank_id=@bankid and chk_reference=@ref and  chk_amount=@amount and chk_date=@date ";
                comm.Parameters.Add("@bankid", SqlDbType.Int).Value = rg.intC3;
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1;
                comm.Parameters.Add("@date", SqlDbType.VarChar).Value = rg.strC2;
                comm.Parameters.Add("@amount", SqlDbType.VarChar).Value = rg.strC4;
                object obj = comm.ExecuteScalar();
                if (obj != null)
                {

                    chkid = int.Parse(comm.ExecuteScalar().ToString());
                }

                comm.Parameters.Clear();

                if (chkid == 0)
                {
                    comm.CommandText = " insert into tbl_cheque ( chk_dep_id, chk_bank_id, chk_reference, chk_date, chk_amount, chk_client, chk_company, chk_account, chk_date_process) values (@depid, @bankid, @ref, @date, @amount,@client,@company,@account,@dateprocess) ";
                    comm.Parameters.Add("@depid", SqlDbType.Int).Value = rg.intC2;
                    comm.Parameters.Add("@bankid", SqlDbType.Int).Value = rg.intC3;
                    comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1;
                    comm.Parameters.Add("@date", SqlDbType.VarChar).Value = rg.strC2;
                    comm.Parameters.Add("@amount", SqlDbType.VarChar).Value = rg.strC4;
                    comm.Parameters.Add("@client", SqlDbType.VarChar).Value = rg.strC5;
                    comm.Parameters.Add("@company", SqlDbType.Int).Value = rg.intC5;
                    comm.Parameters.Add("@account", SqlDbType.Int).Value = rg.intC6;
                    comm.Parameters.Add("@dateprocess", SqlDbType.VarChar).Value = rg.strC3;
                    comm.ExecuteNonQuery();

                    comm.CommandText = " select max(chk_id) from tbl_cheque ";
                    comm.Parameters.Clear();
                    reader = comm.ExecuteReader();

                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0)) result = reader.GetInt32(0); //chkid
                    }
                    reader.Close();
                }
                else
                {
                    result = -1;
                }
            }
            else
            {
                comm.CommandText = " update tbl_cheque set  chk_reference=@ref, chk_bank_id=@bankid, chk_date=@date, chk_amount=@amount, chk_client=@client, chk_company=@company, chk_account=@account, chk_date_process=@dateprocess  where chk_id=@id ";
                comm.Parameters.Add("@id", SqlDbType.Int).Value = rg.intC1;
                comm.Parameters.Add("@bankid", SqlDbType.Int).Value = rg.intC3;
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1;
                comm.Parameters.Add("@date", SqlDbType.VarChar).Value = rg.strC2;
                comm.Parameters.Add("@amount", SqlDbType.VarChar).Value = rg.strC4;
                comm.Parameters.Add("@client", SqlDbType.VarChar).Value = rg.strC5;
                comm.Parameters.Add("@company", SqlDbType.Int).Value = rg.intC5;
                comm.Parameters.Add("@account", SqlDbType.Int).Value = rg.intC6;
                comm.Parameters.Add("@dateprocess", SqlDbType.VarChar).Value = rg.strC3;
                comm.ExecuteNonQuery();

                result = rg.intC1;
            }







            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = 0;
        }
        return result;
    }
    public static Int64 addTrans(int dep, RE_GenericBean rg)
    {
        Int64 result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;


        RE_GenericBean rgb = new RE_GenericBean();
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            int existe = 0;
            if (rg.intC1 == 0)
            {// si es nuevo agrego

                //primero veo que la referencia de la tran no exita
                comm.CommandText = "select pay_deppay_id,pay_tran_date,pay_tran_amount from tbl_paypal_tran  where pay_tran_reference=@ref";
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1.Trim();

                reader = comm.ExecuteReader();
                comm.Parameters.Clear();
                while (reader.Read())
                {
                    if (!reader.IsDBNull(0)) existe = 1;
                }
                reader.Close();

                if (existe == 0)
                {

                    comm.CommandText = " INSERT INTO tbl_paypal_tran (pay_deppay_id, pay_tran_reference, pay_tran_date, pay_tran_amount,  pay_trandate_process, pay_tran_receipt, pay_tran_client) VALUES  (@depid,@ref,@date,@amount,@dateprocess,@receipt,@client)";
                    comm.Parameters.Add("@depid", SqlDbType.Int).Value = rg.intC2;
                    comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1.Trim();
                    comm.Parameters.Add("@date", SqlDbType.VarChar).Value = rg.strC2;
                    comm.Parameters.Add("@amount", SqlDbType.VarChar).Value = rg.strC4;
                    comm.Parameters.Add("@dateprocess", SqlDbType.VarChar).Value = rg.strC3;
                    comm.Parameters.Add("@receipt", SqlDbType.VarChar).Value = rg.strC5;
                    comm.Parameters.Add("@client", SqlDbType.VarChar).Value = rg.strC6;
                    comm.ExecuteNonQuery();

                    comm.CommandText = " select max(pay_tranid) from tbl_paypal_tran ";

                    reader = comm.ExecuteReader();
                    comm.Parameters.Clear();
                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0)) result = reader.GetInt64(0); //chkid
                    }
                    reader.Close();
                }
                else
                {
                    result = -1;
                }
            }
            else
            {
                comm.CommandText = " update tbl_paypal_tran  set  pay_tran_reference=@ref,  pay_tran_date=@date, pay_tran_amount=@amount,  pay_trandate_process=@dateprocess , pay_tran_receipt=@receipt, pay_tran_client=@client where pay_tranid=@id ";
                comm.Parameters.Add("@id", SqlDbType.Int).Value = rg.intC1;
                comm.Parameters.Add("@client", SqlDbType.VarChar).Value = rg.strC6;
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = rg.strC1.Trim();
                comm.Parameters.Add("@date", SqlDbType.VarChar).Value = rg.strC2;
                comm.Parameters.Add("@amount", SqlDbType.VarChar).Value = rg.strC4;
                comm.Parameters.Add("@receipt", SqlDbType.VarChar).Value = rg.strC5;
                comm.Parameters.Add("@dateprocess", SqlDbType.VarChar).Value = rg.strC3;
                comm.ExecuteNonQuery();

                result = rg.intC1;
            }







            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = 0;
        }
        return result;
    }

    public static RE_GenericBean setUnPaid(ArrayList array, string p)
    {
        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlTransaction transaccion;

        conn = DB.OpenConnection();
        transaccion = conn.BeginTransaction();
        SqlCommand comm;

        try
        {


            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaccion;
            comm.CommandType = CommandType.Text;
            int status = 0;
            foreach (RE_GenericBean rg in array)
            {
                int bandera = 0;
                SqlDataReader reader = null;
                comm.CommandText = "select paid, status_id from [ORDER] where order_id=@orden ";
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                reader = comm.ExecuteReader();
                while (reader.Read())
                {
                    string paid = "";
                    if (!reader.IsDBNull(0)) paid = reader.GetString(0);
                    if (!reader.IsDBNull(1)) status = reader.GetInt32(1);
                    if (paid.ToUpper().Equals("YES"))
                    {
                        bandera = 1;
                    }
                }
                reader.Close();
                comm.Parameters.Clear();



                //sI Bandera=0 es porque no esta la orden asignada a ningun cheque, entonces agrego el reg en tbl_cheque_orden 
                //y escribo el #cheuqe en la orden

                if (bandera == 1)
                {

                    //guardo info de orden
                    comm.CommandText = "update [ORDER] set fee=@fee, paid=NULL , paid_date=NULL, check#= NULL  WHERE order_id=@orden ";
                    comm.Parameters.Add("@fee", SqlDbType.VarChar).Value = rg.strC2;
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();

                    //si el status = 5 (pagada) debe regresar a (3) completed
                    if (status == 5)
                    {


                        comm.CommandText = "update [ORDER] set status_id=3,WHERE order_id=@orden ";
                        comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                        comm.ExecuteNonQuery();
                        comm.Parameters.Clear();

                    }
                    comm.CommandText = "delete from  tbl_cheque_orden where  cor_order_id=@orden";
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;

                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                    result.intC1 = 1;


                }
                else
                {
                    result.intC1 = 0;
                    result.strC1 = " This order is not paid";
                }



            }
            transaccion.Commit();
            conn.Close();
        }
        catch (Exception e)
        {
            result.intC1 = 0;
            Utility.writeError(e.Message + "/n /t " + e.Message);
            transaccion.Rollback();
        }
        finally
        {
            if (conn != null) conn.Close();
        }
        return result;
    }


    public static RE_GenericBean setUnPaidClient(ArrayList array, string p)
    {//marca como no pagadas las ordenes del ciente en su doble contabilidad
        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlTransaction transaccion;

        conn = DB.OpenConnection();
        transaccion = conn.BeginTransaction();
        SqlCommand comm;

        try
        {


            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaccion;
            comm.CommandType = CommandType.Text;
            int status = 0;
            foreach (RE_GenericBean rg in array)
            {
                int bandera = 0;
                SqlDataReader reader = null;
                comm.CommandText = "select paid_client, status_id from [ORDER] where order_id=@orden ";
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                reader = comm.ExecuteReader();
                while (reader.Read())
                {
                    string paid = "";
                    if (!reader.IsDBNull(0)) paid = reader.GetString(0);
                    if (!reader.IsDBNull(1)) status = reader.GetInt32(1);
                    if (paid.ToUpper().Equals("YES"))
                    {
                        bandera = 1;
                    }
                }
                reader.Close();
                comm.Parameters.Clear();



                //sI Bandera=0 es porque no esta la orden asignada a ningun cheque, entonces agrego el reg en tbl_cheque_orden 
                //y escribo el #cheuqe en la orden

                if (bandera == 1)
                {

                    //guardo info de orden
                    comm.CommandText = "update [ORDER] set psfprice=@fee, paid_client='NO' , paid_client_date=NULL   WHERE order_id=@orden ";
                    comm.Parameters.Add("@fee", SqlDbType.VarChar).Value = rg.strC2;
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();


                    result.intC1 = 1;


                }
                else
                {
                    result.intC1 = 0;
                    result.strC1 = " This order is not paid";
                }



            }
            transaccion.Commit();
            conn.Close();
        }
        catch (Exception e)
        {
            result.intC1 = 0;
            Utility.writeError(e.Message + "/n /t " + e.Message);
            transaccion.Rollback();
        }
        finally
        {
            if (conn != null) conn.Close();
        }
        return result;
    }

    public static RE_GenericBean setUnPaidPaypal(ArrayList array, string p)
    {
        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlTransaction transaccion;

        conn = DB.OpenConnection();
        transaccion = conn.BeginTransaction();
        SqlCommand comm;

        try
        {


            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaccion;
            comm.CommandType = CommandType.Text;
            int status = 0;
            foreach (RE_GenericBean rg in array)
            {
                int bandera = 0;
                SqlDataReader reader = null;
                comm.CommandText = "select paid, status_id from [ORDER] where order_id=@orden ";
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                reader = comm.ExecuteReader();
                while (reader.Read())
                {
                    string paid = "";

                    if (!reader.IsDBNull(0)) paid = reader.GetString(0);
                    if (!reader.IsDBNull(1)) status = reader.GetInt32(1);
                    if (paid.ToUpper().Equals("YES"))
                    {
                        bandera = 1;
                    }
                }
                reader.Close();
                comm.Parameters.Clear();



                //sI Bandera=0 es porque no esta la orden asignada a ningun cheque, entonces agrego el reg en tbl_cheque_orden 
                //y escribo el #cheuqe en la orden

                if (bandera == 1)
                {

                    //guardo info de orden 
                    comm.CommandText = "update [ORDER] set fee=@fee, paid=NULL , paid_date=NULL, check#=NULL  WHERE order_id=@orden ";
                    comm.Parameters.Add("@fee", SqlDbType.VarChar).Value = rg.strC2;
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();




                    comm.CommandText = "delete from  tlb_paytran_order where  payord_order=@orden";
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = rg.strC1;

                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                    result.intC1 = 1;


                }
                else
                {
                    result.intC1 = 0;
                    result.strC1 = " This order is not paid";
                }



            }
            transaccion.Commit();
            conn.Close();
        }
        catch (Exception e)
        {
            result.intC1 = 0;
            Utility.writeError(e.Message + "/n /t " + e.Message);
            transaccion.Rollback();
        }
        finally
        {
            if (conn != null) conn.Close();
        }
        return result;
    }

    public static DataSet getSectionPage(string pageID)
    {
        RE_GenericBean result = null;
        DataSet res = new DataSet();
        res.Tables.Add("Tabla");
        res.Tables["Tabla"].Columns.Add("section_id");
        res.Tables["Tabla"].Columns.Add("section_name");
        res.Tables["Tabla"].Columns.Add("papp_id");
        res.Tables["Tabla"].Columns.Add("orden");
        try
        {
            SqlConnection conn = null;
            conn = OpenConnection2();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT   section_id, section_name, sec_papp_id, orden   FROM   tbl_section_page   WHERE   (sec_papp_id = @pageid)   ORDER BY orden ";
            comm.Parameters.Add("@pageid", SqlDbType.Int).Value = pageID;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                result = new RE_GenericBean();
                if (!reader.IsDBNull(0)) result.intC1 = reader.GetInt32(0); // section_id
                if (!reader.IsDBNull(1)) result.strC1 = reader.GetString(1); // section_name
                if (!reader.IsDBNull(2)) result.intC2 = reader.GetInt32(2); // sec_papp_id
                if (!reader.IsDBNull(3)) result.intC3 = reader.GetInt32(3); // orden
                object[] obj = { result.intC1, result.strC1, result.intC2, result.intC3 };
                res.Tables["Tabla"].Rows.Add(obj);
            }
            reader.Close();
            comm.Parameters.Clear();
            conn.Close();
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            res = null;
        }
        return res;
    }

    public static DataSet getReportClient(string where)
    {

        DataSet result = new DataSet();
        RE_GenericBean temp;
        double promgeneral = 0;
        double promgeneralneg = 0;
        double promgeneraligual = 0;
        int conteogeneral = 0;
        double prom = 0;
        int conteogeneralneg = 0;
        int conteogeneraligual = 0;
        double suma = 0;
        double sumaneg = 0;
        double sumaigual = 0;
        double diferencia = 0;
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("#");
        result.Tables["Tabla"].Columns.Add("Order");
        result.Tables["Tabla"].Columns.Add("St");
        result.Tables["Tabla"].Columns.Add("Street Address");
        result.Tables["Tabla"].Columns.Add("City");
        result.Tables["Tabla"].Columns.Add("County");
        result.Tables["Tabla"].Columns.Add("Sector");
        result.Tables["Tabla"].Columns.Add("Area");
        result.Tables["Tabla"].Columns.Add("Report #1 Value");
        result.Tables["Tabla"].Columns.Add("Report #2 Value");
        result.Tables["Tabla"].Columns.Add("Difference +/- ($)");
        result.Tables["Tabla"].Columns.Add("Difference +/- (%)");

        result.Tables.Add("Tabla2");
        result.Tables["Tabla2"].Columns.Add("# pos");
        result.Tables["Tabla2"].Columns.Add("porcentaje pos");
        result.Tables["Tabla2"].Columns.Add("# neg");
        result.Tables["Tabla2"].Columns.Add("porcentaje neg");
        result.Tables["Tabla2"].Columns.Add("# igual");
        result.Tables["Tabla2"].Columns.Add("porcentaje igual");

        try
        {
            if (!where.Equals("")) { where += " and "; }
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT  distinct [ORDER].ordernum, [ORDER].stnum, [ORDER].stadd, [ORDER].stcity, [ORDER].county, [ORDER].ord_sector, [ORDER].ord_area, [ORDER].order_id, [ORDER_FAIL].date    FROM  ORDER_FAIL, [ORDER]   WHERE  " + where + "  [ORDER_FAIL].fail_id=2 and [ORDER_FAIL].order_id= [ORDER].order_id and [ORDER_FAIL].completed = 'YES'   ORDER BY [ORDER_FAIL].date ";

            reader = comm.ExecuteReader();
            int cont = 0;
            while (reader.Read())
            {
                temp = new RE_GenericBean();

                if (!reader.IsDBNull(0)) temp.strC1 = reader.GetString(0); // ordernum
                if (!reader.IsDBNull(1)) temp.strC2 = reader.GetString(1); // stnum
                if (!reader.IsDBNull(2)) temp.strC3 = Utility.toCapital(reader.GetString(2)); // stadd
                if (!reader.IsDBNull(3)) temp.strC4 = Utility.toCapital(reader.GetString(3)); // city
                if (!reader.IsDBNull(4)) temp.intC2 = reader.GetInt32(4); // county
                if (!reader.IsDBNull(5)) temp.intC3 = reader.GetInt32(5); // sector
                if (!reader.IsDBNull(6)) temp.intC4 = reader.GetInt32(6); // area
                if (!reader.IsDBNull(7)) temp.intC1 = reader.GetInt32(7); // order_id
                cont++;
                DataSet sectors = getSectors();
                DataSet counties = getAllCounties();
                DataSet comps = getComps(temp.intC1);
                DataSet area = getAreas();

                for (int i = 0; i < counties.Tables[0].Rows.Count; i++)
                {
                    if (counties.Tables[0].Rows[i][0].ToString().Equals(temp.intC2.ToString()))
                    {
                        temp.strC5 = Utility.toCapital(counties.Tables[0].Rows[i][1].ToString());
                    }

                }
                for (int i = 0; i < sectors.Tables[0].Rows.Count; i++)
                {
                    if (sectors.Tables[0].Rows[i][0].ToString().Equals(temp.intC3.ToString()))
                    {
                        temp.strC6 = Utility.toCapital(sectors.Tables[0].Rows[i][1].ToString());
                    }

                }

                for (int i = 0; i < area.Tables[0].Rows.Count; i++)
                {
                    if (area.Tables[0].Rows[i][0].ToString().Equals(temp.intC4.ToString()))
                    {
                        temp.strC7 = Utility.toCapital(area.Tables[0].Rows[i][1].ToString());
                    }

                }

                string report1 = ""; String report2 = "";
                diferencia = 0;

                for (int i = 0; i < comps.Tables[0].Rows.Count; i++)
                {
                    string ahora2 = comps.Tables[0].Rows[i][10].ToString();
                    if (comps.Tables[0].Rows[i][21].ToString().ToUpper().Equals("YES"))
                    {
                        if (i != 0)
                        {
                            //temp.strC1 = ""; temp.strC2 = ""; temp.strC3 = ""; temp.strC4 = ""; temp.strC5 = ""; temp.strC6 = ""; temp.strC7 = "";
                            // string ant2 = comps.Tables[0].Rows[lastindex][10].ToString();
                            report2 = comps.Tables[0].Rows[i][10].ToString();
                            long a = 1;
                            long b = 1;
                            try
                            {

                                if (!report2.Equals("")) { b = long.Parse(report2); /*presente comp*/ }
                                if (!report1.Equals("")) { a = long.Parse(report1); /*primer comp*/ }
                                diferencia = a - b;
                                double d = 0;
                                if (a != 0) { d = ((100 * (diferencia)) / a); }
                                temp.strC8 = diferencia.ToString();
                                if (diferencia == 0)
                                {
                                    temp.strC8 = "N/A";

                                }
                                temp.strC9 = String.Format("{0:0.##}", d) + " % ";
                                suma = d;

                                if (d == 0)
                                {
                                    temp.strC9 = "N/A";
                                }




                            }
                            catch (Exception e)
                            {

                                HttpContext.Current.Response.Write("<script> alert('Error " + e.Message + " " + e.StackTrace + "');</script>");

                            }


                        }
                        else
                        {
                            report1 = comps.Tables[0].Rows[0][10].ToString();

                        }


                    }

                }
                object[] obj = { cont, temp.strC1, temp.strC2, temp.strC3, temp.strC4, temp.strC5, temp.strC6, temp.strC7, report2, report1, temp.strC8, temp.strC9 };
                result.Tables["Tabla"].Rows.Add(obj);
                if (suma == 0) { promgeneraligual += suma; conteogeneraligual++; } else if (suma < 0) { promgeneralneg += suma; conteogeneralneg++; } else if (suma > 0) { promgeneral += suma; conteogeneral++; }


            }
            reader.Close();
            comm.Parameters.Clear();
            conn.Close();

            if (conteogeneral != 0) { promgeneral = (conteogeneral * 100) / cont; }
            if (conteogeneralneg != 0) { promgeneralneg = (conteogeneralneg * 100) / cont; }
            if (conteogeneraligual != 0) { promgeneraligual = (conteogeneraligual * 100) / cont; }
            string t = String.Format("{0:0.##}", promgeneral);
            string t1 = String.Format("{0:0.##}", promgeneralneg);
            string t2 = String.Format("{0:0.##}", promgeneraligual);
            result.Tables["Tabla2"].Rows.Add(conteogeneral, t, conteogeneralneg, t1, conteogeneraligual, t2);
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            result = null;
        }


        return result;
    }

    public static REPORTDS getReportClientdsr(string where, string period)
    {
        REPORTDS dsrep = new REPORTDS();
        DataSet result = new DataSet();
        RE_GenericBean temp;
        double promgeneral = 0;
        double promgeneralneg = 0;
        double promgeneraligual = 0;
        int conteogeneral = 0;
        double prom = 0;
        int conteogeneralneg = 0;
        int conteogeneraligual = 0;
        double suma = 0;
        double sumaneg = 0;
        double sumaigual = 0;
        double diferencia = 0;
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("#");
        result.Tables["Tabla"].Columns.Add("Order");
        result.Tables["Tabla"].Columns.Add("St");
        result.Tables["Tabla"].Columns.Add("Street Address");
        result.Tables["Tabla"].Columns.Add("City");
        result.Tables["Tabla"].Columns.Add("County");
        result.Tables["Tabla"].Columns.Add("Sector");
        result.Tables["Tabla"].Columns.Add("Area");
        result.Tables["Tabla"].Columns.Add("Report #1 Value");
        result.Tables["Tabla"].Columns.Add("Report #2 Value");
        result.Tables["Tabla"].Columns.Add("Difference +/- ($)");
        result.Tables["Tabla"].Columns.Add("Difference +/- (%)");

        result.Tables.Add("Tabla2");
        result.Tables["Tabla2"].Columns.Add("# pos");
        result.Tables["Tabla2"].Columns.Add("porcentaje pos");
        result.Tables["Tabla2"].Columns.Add("# neg");
        result.Tables["Tabla2"].Columns.Add("porcentaje neg");
        result.Tables["Tabla2"].Columns.Add("# igual");
        result.Tables["Tabla2"].Columns.Add("porcentaje igual");

        try
        {
            if (!where.Equals("")) { where += " and "; }
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT  distinct [ORDER].ordernum, [ORDER].stnum, [ORDER].stadd, [ORDER].stcity, [ORDER].county, [ORDER].ord_sector, [ORDER].ord_area, [ORDER].order_id, [ORDER_FAIL].date    FROM  ORDER_FAIL, [ORDER]   WHERE  " + where + "  [ORDER_FAIL].fail_id=2 and [ORDER_FAIL].order_id= [ORDER].order_id and [ORDER_FAIL].completed = 'YES'   ORDER BY [ORDER_FAIL].date ";

            reader = comm.ExecuteReader();
            int cont = 0;
            while (reader.Read())
            {
                temp = new RE_GenericBean();

                if (!reader.IsDBNull(0)) temp.strC1 = reader.GetString(0); // ordernum
                if (!reader.IsDBNull(1)) temp.strC2 = reader.GetString(1); // stnum
                if (!reader.IsDBNull(2)) temp.strC3 = Utility.toCapital(reader.GetString(2)); // stadd
                if (!reader.IsDBNull(3)) temp.strC4 = Utility.toCapital(reader.GetString(3)); // city
                if (!reader.IsDBNull(4)) temp.intC2 = reader.GetInt32(4); // county
                if (!reader.IsDBNull(5)) temp.intC3 = reader.GetInt32(5); // sector
                if (!reader.IsDBNull(6)) temp.intC4 = reader.GetInt32(6); // area
                if (!reader.IsDBNull(7)) temp.intC1 = reader.GetInt32(7); // order_id
                cont++;
                DataSet sectors = getSectors();
                DataSet counties = getAllCounties();
                DataSet comps = getComps(temp.intC1);
                DataSet area = getAreas();

                for (int i = 0; i < counties.Tables[0].Rows.Count; i++)
                {
                    if (counties.Tables[0].Rows[i][0].ToString().Equals(temp.intC2.ToString()))
                    {
                        temp.strC5 = Utility.toCapital(counties.Tables[0].Rows[i][1].ToString());
                    }

                }
                for (int i = 0; i < sectors.Tables[0].Rows.Count; i++)
                {
                    if (sectors.Tables[0].Rows[i][0].ToString().Equals(temp.intC3.ToString()))
                    {
                        temp.strC6 = Utility.toCapital(sectors.Tables[0].Rows[i][1].ToString());
                    }

                }

                for (int i = 0; i < area.Tables[0].Rows.Count; i++)
                {
                    if (area.Tables[0].Rows[i][0].ToString().Equals(temp.intC4.ToString()))
                    {
                        temp.strC7 = Utility.toCapital(area.Tables[0].Rows[i][1].ToString());
                    }

                }

                string report1 = ""; String report2 = "";
                diferencia = 0;

                for (int i = 0; i < comps.Tables[0].Rows.Count; i++)
                {
                    string ahora2 = comps.Tables[0].Rows[i][10].ToString();
                    if (comps.Tables[0].Rows[i][21].ToString().ToUpper().Equals("YES"))
                    {
                        if (i != 0)
                        {
                            //temp.strC1 = ""; temp.strC2 = ""; temp.strC3 = ""; temp.strC4 = ""; temp.strC5 = ""; temp.strC6 = ""; temp.strC7 = "";
                            // string ant2 = comps.Tables[0].Rows[lastindex][10].ToString();
                            report2 = comps.Tables[0].Rows[i][10].ToString();
                            long a = 1;
                            long b = 1;
                            try
                            {

                                if (!report2.Equals("")) { b = long.Parse(report2); /*presente comp*/ }
                                if (!report1.Equals("")) { a = long.Parse(report1); /*primer comp*/ }
                                diferencia = a - b;
                                double d = 0;
                                if (a != 0) { d = ((100 * (diferencia)) / a); }
                                temp.strC8 = diferencia.ToString();
                                if (diferencia == 0)
                                {
                                    temp.strC8 = "N/A";

                                }
                                temp.strC9 = String.Format("{0:0.##}", d) + " % ";
                                suma = d;

                                if (d == 0)
                                {
                                    temp.strC9 = "N/A";
                                }




                            }
                            catch (Exception e)
                            {

                                HttpContext.Current.Response.Write("<script> alert('Error " + e.Message + " " + e.StackTrace + "');</script>");

                            }


                        }
                        else
                        {
                            report1 = comps.Tables[0].Rows[0][10].ToString();

                        }


                    }

                }
                object[] obj = { cont, temp.strC1, temp.strC2, temp.strC3, temp.strC4, temp.strC5, temp.strC6, temp.strC7, report2, report1, temp.strC8, temp.strC9 };
                dsrep.order.AddorderRow(cont.ToString(), temp.strC1, temp.strC2, temp.strC3, temp.strC4, temp.strC5, temp.strC6, temp.strC7, report2, report1, temp.strC8, temp.strC9, "", "", "", "");
                result.Tables["Tabla"].Rows.Add(obj);
                if (suma == 0) { promgeneraligual += suma; conteogeneraligual++; } else if (suma < 0) { promgeneralneg += suma; conteogeneralneg++; } else if (suma > 0) { promgeneral += suma; conteogeneral++; }


            }
            reader.Close();
            comm.Parameters.Clear();
            conn.Close();

            if (conteogeneral != 0) { promgeneral = (conteogeneral * 100) / cont; }
            if (conteogeneralneg != 0) { promgeneralneg = (conteogeneralneg * 100) / cont; }
            if (conteogeneraligual != 0) { promgeneraligual = (conteogeneraligual * 100) / cont; }
            string t = String.Format("{0:0.##}", promgeneral);
            string t1 = String.Format("{0:0.##}", promgeneralneg);
            string t2 = String.Format("{0:0.##}", promgeneraligual);
            result.Tables["Tabla2"].Rows.Add(conteogeneral, t, conteogeneralneg, t1, conteogeneraligual, t2);
            dsrep.datos.AdddatosRow(period, conteogeneral.ToString(), conteogeneralneg.ToString(), conteogeneraligual.ToString(), t.ToString(), null);
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            result = null;
        }


        return dsrep;
    }

    public static DataSet getAreasbySector(string sector)
    {
        DataSet result = new DataSet();
        RE_GenericBean rgb = null;
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("area_id");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("enable");//2
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " select sa.area_id, a.name , a.enable from sector_area sa, area a  where sector_id=" + sector + " and sa.area_id = a.area_id";
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//area_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2);//enable
                object[] objArr = { rgb.intC1, rgb.strC1, rgb.intC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            conn.Close();
            reader.Dispose();

        }



        return result;
    }

    public static DataSet getCountiesbyArea(string county_id)
    {
        DataSet result = new DataSet();
        RE_GenericBean rgb = null;
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("county_id");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("enable");//2
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT DISTINCT  COUNTY.county_id, COUNTY.name, COUNTY.enable  FROM         SECTOR_AREA INNER JOIN    ZIPCODE ON SECTOR_AREA.area_id = ZIPCODE.area_id INNER JOIN   CITY INNER JOIN  COUNTY ON CITY.county_id = COUNTY.county_id ON ZIPCODE.city = CITY.city_id WHERE     (SECTOR_AREA.area_id = " + county_id + ")";
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//county_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.intC2 = reader.GetInt32(2);//enable
                object[] objArr = { rgb.intC1, rgb.strC1, rgb.intC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            conn.Close();
            reader.Dispose();

        }



        return result;
    }

    public static int deleteTrans(int dep, int tran)
    {
        int result = 0;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;

        SqlTransaction transaccion;
        conn = OpenConnection();
        transaccion = conn.BeginTransaction();

        RE_GenericBean rgb = new RE_GenericBean();
        try
        {


            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.Transaction = transaccion;


            //primero obtengo todas las ordenes asociadas a esta transaccion
            comm.CommandText = "select payord_order from tlb_paytran_order where payord_tranid=@tranid";
            comm.Parameters.Add("@tranid", SqlDbType.VarChar).Value = tran;
            reader = comm.ExecuteReader();
            comm.Parameters.Clear();
            ArrayList ordenes = new ArrayList();
            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) ordenes.Add(reader.GetInt32(0));


            }
            reader.Close();
            //segundo actualizo todas las ordenes y las quito de la asociacion a esta tran
            for (int i = 0; i < ordenes.Count; i++)
            {
                comm.CommandText = "update [ORDER] set  paid=NULL , paid_date=NULL, check#=NULL  WHERE order_id=@orden ";
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = (int)ordenes[i];
                comm.ExecuteNonQuery();
                comm.Parameters.Clear();



                comm.CommandText = "delete from  tlb_paytran_order where  payord_order=@orden";
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = (int)ordenes[i];

                comm.ExecuteNonQuery();
                comm.Parameters.Clear();

            }

            // tercero quito la transaccion 

            comm.CommandText = "delete from  [tbl_paypal_tran]   WHERE pay_tranid=@tran";
            comm.Parameters.Add("@tran", SqlDbType.Int).Value = tran;
            comm.ExecuteNonQuery();
            transaccion.Commit();








            conn.Close();


        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace);
            result = 0;
            transaccion.Rollback();
        }
        return result;
    }

    public static RE_GenericBean getExtraFeebyCounty(int countyid, int productid)
    {
        RE_GenericBean result = new RE_GenericBean();
        RE_GenericBean rgb = null;

        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT increment from PRODUCT_COUNTY where product_id=@product and county_id=@county ";
            comm.Parameters.Add("@product", SqlDbType.Int).Value = productid;
            comm.Parameters.Add("@county", SqlDbType.Int).Value = countyid;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) result.doubleC1 = reader.GetFloat(0);//increment
                result.intC1 = 1;

            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            conn.Close();
            if (reader != null)
                reader.Dispose();

        }



        return result;
    }

    public static REPORTDS getReportEval(string where)
    {
        throw new NotImplementedException();
    }

    public static DataSet getFailTypes()
    {
        DataSet result = new DataSet();
        RE_GenericBean rgb = null;
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("id");//1
        result.Tables["Tabla"].Columns.Add("name");//2
        result.Tables["Tabla"].Columns.Add("descripcion");//2
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT fail_id, name, description  FROM FAIL ";
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0);//fail_id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//name
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//descripcion
                object[] objArr = { rgb.intC1, rgb.strC1, rgb.strC2 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            conn.Close();
            reader.Dispose();

        }



        return result;
    }

    public static REPORTDS getFailReport(string where, string period, string filtro)
    {
        REPORTDS result = new REPORTDS();
        //DataSet result = new DataSet();
        RE_GenericBean temp;

        try
        {
            if (!where.Equals("")) { where += " and "; }
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlConnection conn2 = null;
            conn2 = OpenConnection();
            SqlDataReader reader;
            SqlDataReader reader2;
            SqlCommand comm = new SqlCommand();
            SqlCommand comm2 = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT [ORDER_FAIL].order_fail_id, [ORDER].order_id, [ORDER].ordernum,  convert( varchar, [ORDER_FAIL].date) date , [ORDER_FAIL].agent,case when [ORDER_FAIL].fail_id=4 then   [ORDER].ord_uploadby else [ORDER].ord_processor end, convert(varchar, [ORDER_FAIL].fail_id),convert( varchar, [order].ord_submitted_date),[ORDER].ord_qc,[ORDER_FAIL].comments    FROM  ORDER_FAIL, [ORDER]   WHERE  " + where + "   [ORDER_FAIL].order_id= [ORDER].order_id and [ORDER_FAIL].completed = 'YES'   ORDER BY   convert(varchar,[ORDER_FAIL].date)  asc,[ORDER_FAIL].agent  , convert(varchar,[ORDER_FAIL].fail_id) asc";

            reader = comm.ExecuteReader();
            int cont = 0;
            while (reader.Read())
            {
                temp = new RE_GenericBean();
                if (!reader.IsDBNull(0)) temp.intC1 = reader.GetInt32(0); // failid
                if (!reader.IsDBNull(1)) temp.intC2 = reader.GetInt32(1); // orderid
                if (!reader.IsDBNull(2)) temp.strC1 = reader.GetString(2); // ordernum
                if (!reader.IsDBNull(3)) temp.strC2 = reader.GetString(3); // date
                if (!reader.IsDBNull(4)) temp.strC3 = reader.GetString(4); // agent
                if (!reader.IsDBNull(5)) temp.strC4 = reader.GetString(5); // pprocessor
                if (!reader.IsDBNull(6)) temp.strC5 = reader.GetString(6); // failid
                if (!reader.IsDBNull(7)) temp.strC6 = reader.GetString(7); // submitted date
                if (!reader.IsDBNull(8)) temp.strC7 = reader.GetString(8); // qc
                if (!reader.IsDBNull(9)) temp.strC8 = reader.GetString(9); // comments



                //ahorita veo cual es el numro de orden y busco su historial en fallos
                comm2.Connection = conn2;
                comm2.CommandType = CommandType.Text;
                comm2.CommandText = "select order_fail_id, date, agent, qc from order_fail where order_id=@id and completed='YES'";
                comm2.Parameters.Add("@id", SqlDbType.Int).Value = temp.intC2;
                reader2 = comm2.ExecuteReader();
                comm2.Parameters.Clear();
                cont = 0;
                string old = "";
                string oldqc = "";
                string temporal = "";
                string temporalqc = "";
                while (reader2.Read())
                {
                    RE_GenericBean temp2 = new RE_GenericBean();
                    if (!reader2.IsDBNull(0)) temp2.intC1 = reader2.GetInt32(0); // failid
                    if (!reader2.IsDBNull(2)) temp2.strC1 = reader2.GetString(2); // agent actual
                    if (!reader2.IsDBNull(3)) temp2.strC2 = reader2.GetString(3); // agentqc actual

                    if (cont == 0)
                    {
                        temporal = temp2.strC1;//actual proc
                        temporalqc = temp2.strC2;//actualqc
                    }


                    if (cont > 0)
                    {
                        if (temp.strC5.Trim().Equals("1") || temp.strC5.Trim().Equals("5"))
                        {
                            old = temporal;
                            oldqc = temporalqc;
                            temporal = temp2.strC1;
                            temporalqc = temp2.strC2;
                            if (temp.intC1 == temp2.intC1)
                            {
                                temp.strC4 = old;//old proc
                                temp.strC7 = oldqc;//old qc

                            }
                        }

                    }



                    cont++;
                }

                reader2.Close();
                int agregar = 0;
                if (filtro.Equals(""))
                {
                    agregar = 1;
                }
                else
                {
                    if (temp.strC4.Equals(filtro) || temp.strC7.Equals(filtro))
                    {
                        agregar = 1;
                    }

                }
                if (agregar == 1)
                {
                    object[] obj = { temp.intC1.ToString(), temp.intC2.ToString(), temp.strC1, temp.strC2, temp.strC3, temp.strC4, temp.strC5, temp.strC6, temp.strC7, temp.strC8, "", "", "", "", "", "" };
                    result.Tables["order"].Rows.Add(obj);
                }



            }
            reader.Close();
            comm.Parameters.Clear();
            conn.Close();

            comm2.Parameters.Clear();
            conn2.Close();

        }
        catch (Exception e)
        {
            Utility.writeError("Error Fail Report " + e.Message + e.StackTrace);
            result = null;
        }


        return result;
    }

    public static RE_GenericBean hasAlerts(string alias)
    {
        RE_GenericBean re = new RE_GenericBean();



        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT id, toagent, fromagent, message, status, convert(varchar,date,101), convert(varchar,time) from alert where status=1 and toagent=@alias ";
            comm.Parameters.Add("@alias", SqlDbType.VarChar).Value = alias;

            reader = comm.ExecuteReader();

            while (reader.Read())
            {

                if (!reader.IsDBNull(0)) re.intC2 = reader.GetInt32(0);//id
                if (!reader.IsDBNull(1)) re.strC1 = reader.GetString(1);//toagent
                if (!reader.IsDBNull(2)) re.strC2 = reader.GetString(2);//fromagent
                if (!reader.IsDBNull(3)) re.strC3 = reader.GetString(3);//message
                if (!reader.IsDBNull(4)) re.intC3 = reader.GetInt32(4);//status
                if (!reader.IsDBNull(5)) re.strC5 = reader.GetString(5);//date
                if (!reader.IsDBNull(6)) re.strC6 = reader.GetString(6);//time

                re.intC1 = 1;

            }
            reader.Close();

        }
        catch (Exception ex)
        {
            re = null;
        }
        finally
        {
            if (conn != null)
                conn.Close();
            if (reader != null)
                reader.Dispose();
        }






        return re;
    }

    public static void deleteAlert(int id)
    {


        SqlCommand comm = null;

        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " update   alert set status=0 where  id=@id ";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = id;

            comm.ExecuteNonQuery();
            comm.Parameters.Clear();


        }
        catch (Exception ex)
        {

            Utility.writeError("Fail on deleteAlert " + ex.Message + ex.StackTrace);
        }
        finally
        {
            conn.Close();

        }
    }

    public static DataSet getAllAlerts()
    {
        DataSet result = new DataSet();
        RE_GenericBean re = null;
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("id");//1
        result.Tables["Tabla"].Columns.Add("toagent");//2
        result.Tables["Tabla"].Columns.Add("fromagent");//2
        result.Tables["Tabla"].Columns.Add("message");//2
        result.Tables["Tabla"].Columns.Add("status");//2
        result.Tables["Tabla"].Columns.Add("date");//2
        result.Tables["Tabla"].Columns.Add("time");//2
        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT id, toagent, fromagent, message, status, convert(varchar,date,101), convert(varchar,time) from alert where status=1 ";


            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                re = new RE_GenericBean();
                if (!reader.IsDBNull(0)) re.intC2 = reader.GetInt32(0);//id
                if (!reader.IsDBNull(1)) re.strC1 = reader.GetString(1);//toagent
                if (!reader.IsDBNull(2)) re.strC2 = reader.GetString(2);//fromagent
                if (!reader.IsDBNull(3)) re.strC3 = reader.GetString(3);//message
                if (!reader.IsDBNull(4)) re.intC3 = reader.GetInt32(4);//status
                if (!reader.IsDBNull(5)) re.strC5 = reader.GetString(5);//date
                if (!reader.IsDBNull(6)) re.strC6 = reader.GetString(6);//time

                object[] objArr = { re.intC2, re.strC1, re.strC2, re.strC3, re.intC3, re.strC5, re.strC6 };
                result.Tables["Tabla"].Rows.Add(objArr);

            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            conn.Close();
            if (reader != null)
                reader.Dispose();
        }

        return result;
    }

    public static int setAlert(RE_GenericBean ra)
    {
        int result = 0;
        SqlCommand comm = null;

        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " insert into    alert (toagent, fromagent,message,status,date,time) values (@to,@from,@msg,1,getdate(),@time) ";
            comm.Parameters.Add("@to", SqlDbType.VarChar).Value = ra.strC1;
            comm.Parameters.Add("@from", SqlDbType.VarChar).Value = ra.strC2;
            comm.Parameters.Add("@msg", SqlDbType.VarChar).Value = ra.strC3;
            comm.Parameters.Add("@time", SqlDbType.VarChar).Value = ra.strC6;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
            result = 1;


        }
        catch (Exception ex)
        {

            Utility.writeError("Fail on InsertAlert " + ex.Message + ex.StackTrace);
            result = 0;
        }
        finally
        {
            conn.Close();

        }
        return result;
    }

    public static DataSet getCatPage(int page_id)
    {
        DataSet result = new DataSet();
        RE_GenericBean re = null;
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("id");
        result.Tables["Tabla"].Columns.Add("name");
        result.Tables["Tabla"].Columns.Add("papp_id");
        result.Tables["Tabla"].Columns.Add("orden");

        SqlCommand comm = null;
        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection2();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT   section_id, section_name, sec_papp_id, orden from tbl_section_page   WHERE   sec_papp_id=@id ORDER BY orden ";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = page_id;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                re = new RE_GenericBean();
                if (!reader.IsDBNull(0)) re.intC1 = reader.GetInt32(0);//section_id
                if (!reader.IsDBNull(1)) re.strC1 = reader.GetString(1);//section_name
                if (!reader.IsDBNull(2)) re.intC2 = reader.GetInt32(2);//sec_papp_id
                if (!reader.IsDBNull(3)) re.intC3 = reader.GetInt32(3);//orden

                object[] objArr = { re.intC1, re.strC1, re.intC2, re.intC3 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
        }
        catch (Exception ex)
        {
            result = null;
        }
        finally
        {
            conn.Close();
            reader.Dispose();
        }
        return result;
    }

    public static int InsertSection(int page, string name)
    {
        int result = 0;
        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        conn = OpenConnection2();
        transaction = conn.BeginTransaction();

        try
        {
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaction;
            comm.CommandType = CommandType.Text;
            int orden = 0;
            if (page != null)
            {
                comm.CommandText = " SELECT MAX(orden)  FROM  tbl_section_page  WHERE  (sec_papp_id = @idpage) ";
                comm.Parameters.Add("@idpage", SqlDbType.Int).Value = page;
                reader = comm.ExecuteReader();

                while (reader.Read())
                {
                    if (!reader.IsDBNull(0)) orden = reader.GetInt32(0);//orden
                }
                comm.Parameters.Clear();
                reader.Close();
                orden = orden + 1;

                comm.CommandText = " INSERT INTO tbl_section_page (section_name, sec_papp_id, orden)  VALUES  (@name, @idpage, @orden) ";
                comm.Parameters.Add("@name", SqlDbType.VarChar).Value = name;
                comm.Parameters.Add("@idpage", SqlDbType.Int).Value = page;
                comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
                comm.ExecuteNonQuery();
                comm.Parameters.Clear();

                transaction.Commit();
                result = 1;
            }
        }
        catch (Exception e)
        {
            transaction.Rollback();
            string ruta = "c:\\TEMP\\archivo.txt";
            StreamWriter escritor = new StreamWriter(ruta, true);
            escritor.WriteLine(e.Message.ToString());
            escritor.Close();
            return 0;
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }

    public static int UpdateSection(int idsection, string name)
    {
        int result = 0;
        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand comm = null;
        conn = OpenConnection2();
        transaction = conn.BeginTransaction();

        try
        {
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaction;
            comm.CommandType = CommandType.Text;

            if (idsection != null)
            {
                comm.CommandText = " UPDATE   tbl_section_page   SET   section_name = @name   WHERE   section_id = @idsection ";
                comm.Parameters.Add("@name", SqlDbType.VarChar).Value = name;
                comm.Parameters.Add("@idsection", SqlDbType.Int).Value = idsection;
                comm.ExecuteNonQuery();
                comm.Parameters.Clear();

                transaction.Commit();
                result = 1;
            }
        }
        catch (Exception e)
        {
            transaction.Rollback();
            string ruta = "c:\\TEMP\\archivo.txt";
            StreamWriter escritor = new StreamWriter(ruta, true);
            escritor.WriteLine(e.Message.ToString());
            escritor.Close();
            return 0;
        }
        finally
        {
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }

    public static int deleteSection(int page, int section1, int section2)
    {
        int result = 0;
        RE_GenericBean info;
        ArrayList options;
        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        conn = OpenConnection2();
        transaction = conn.BeginTransaction();

        try
        {
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaction;
            comm.CommandType = CommandType.Text;
            int orden = 0;
            if (page != null)
            {
                comm.CommandText = " SELECT   MAX(orden) AS orden   FROM   tbl_option   WHERE   (opc_pagina = @page) AND (opc_section = @section) ORDER BY orden ";
                comm.Parameters.Add("@page", SqlDbType.Int).Value = page;
                comm.Parameters.Add("@section", SqlDbType.Int).Value = section2;
                reader = comm.ExecuteReader();

                while (reader.Read())
                {
                    if (!reader.IsDBNull(0)) orden = reader.GetInt32(0);//orden
                }
                comm.Parameters.Clear();
                reader.Close();

                comm.CommandText = " SELECT   opc_id, orden   FROM   tbl_option   WHERE   (opc_pagina = @page) AND (opc_section = @section) ORDER BY orden ";
                comm.Parameters.Add("@page", SqlDbType.Int).Value = page;
                comm.Parameters.Add("@section", SqlDbType.Int).Value = section1;
                reader = comm.ExecuteReader();

                options = new ArrayList();
                while (reader.Read())
                {
                    info = new RE_GenericBean();
                    if (!reader.IsDBNull(0)) info.intC1 = reader.GetInt32(0);//option
                    if (!reader.IsDBNull(1)) info.intC2 = reader.GetInt32(1);//orden
                    options.Add(info);
                }
                comm.Parameters.Clear();
                reader.Close();

                foreach (RE_GenericBean opcion in options)
                {
                    comm.CommandText = " UPDATE   tbl_option   SET   opc_section = @idsection, orden = @orden   WHERE   (opc_pagina = @page) AND (opc_id = @option) ";
                    comm.Parameters.Add("@page", SqlDbType.Int).Value = page;
                    comm.Parameters.Add("@option", SqlDbType.Int).Value = opcion.intC1;
                    comm.Parameters.Add("@idsection", SqlDbType.Int).Value = section2;
                    comm.Parameters.Add("@orden", SqlDbType.Int).Value = (opcion.intC2 + orden);
                    comm.ExecuteNonQuery();
                    comm.Parameters.Clear();
                }
                reader.Close();

                comm.CommandText = " DELETE FROM tbl_section_page   WHERE   (section_id = @section) ";
                comm.Parameters.Add("@section", SqlDbType.Int).Value = section1;
                comm.ExecuteNonQuery();
                comm.Parameters.Clear();

                transaction.Commit();
                result = 1;
            }
        }
        catch (Exception e)
        {
            transaction.Rollback();
            string ruta = "c:\\TEMP\\archivo.txt";
            StreamWriter escritor = new StreamWriter(ruta, true);
            escritor.WriteLine(e.Message.ToString());
            escritor.Close();
            return 0;
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }

    public static void setLog(int order_id, string field, string desc, string user_id)
    {
        SqlCommand comm = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " INSERT INTO  tbl_order_log  (order_id, field, description, user_id, date, time) VALUES (@ordid, @field, @desc, @usid, getdate(), convert(varchar,getdate(),108)) ";
            comm.Parameters.Add("@ordid", SqlDbType.Int).Value = order_id;
            comm.Parameters.Add("@field", SqlDbType.VarChar).Value = field;
            comm.Parameters.Add("@desc", SqlDbType.VarChar).Value = desc;
            comm.Parameters.Add("@usid", SqlDbType.VarChar).Value = user_id;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
        }
        catch (Exception ex)
        {
            Utility.writeError("Fail on insert log " + ex.Message + ex.StackTrace);
        }
        finally
        {
            conn.Close();
        }
    }

    public static int setPaidPaypayAutomatic(RE_GenericBean datos)
    {
        int result = 0;

        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        conn = OpenConnection();
        transaction = conn.BeginTransaction();

        try
        {
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaction;
            comm.CommandType = CommandType.Text;
            int depid = 0;
            int tranid = 0;
            string datedep = "";
            string orders = datos.strC6;
            string[] temporders = orders.Split(';');
            if (datos.strC5.ToUpper() == "COMPLETED")
            {

                comm.CommandText = "  SELECT  MAX(dep_pay_id) AS Expr1, convert( varchar,dep_pay_date,101) date, MONTH(dep_pay_date) AS Expr2 FROM  tbl_dep_pay WHERE     (MONTH(dep_pay_date) = MONTH(GETDATE())) and (YEAR(dep_pay_date)= YEAR(getdate())) GROUP BY dep_pay_date ";
                reader = comm.ExecuteReader();

                while (reader.Read())
                {
                    if (!reader.IsDBNull(0)) depid = reader.GetInt32(0);//dep_pay_id
                    if (!reader.IsDBNull(1)) datedep = reader.GetString(1);//dep_pay_id
                }
                comm.Parameters.Clear();
                reader.Close();

                Utility.writeError("Payapl max deposito pay:" + depid);
                // si no lo encuentra es que en este mes no hay deposito de paypal, lo creo
                if (depid == 0)
                {
                    //creo el deposito

                    comm.Parameters.Clear();
                    comm.CommandText = " INSERT INTO tbl_dep_pay  (dep_pay_reference, dep_pay_date) values (@ref,getdate()) ";
                    comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = "Paypal " + DateTime.Today.Month.ToString();


                    comm.ExecuteNonQuery();
                    comm.CommandText = "  SELECT  MAX(dep_pay_id) AS Expr1, convert( varchar,dep_pay_date,101) date, MONTH(dep_pay_date) AS Expr2 FROM  tbl_dep_pay WHERE     (MONTH(dep_pay_date) = MONTH(GETDATE())) GROUP BY dep_pay_date ";
                    reader = comm.ExecuteReader();

                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0)) depid = reader.GetInt32(0);//dep_pay_id
                        if (!reader.IsDBNull(1)) datedep = reader.GetString(1);//dep_pay_date
                    }
                    comm.Parameters.Clear();
                    reader.Close();

                }
                Utility.writeError("Payapl max deposito pay2:" + depid);
                //obtengo datos a llenar del cliente como account y company
                string account = "0"; DataSet dsacc;
                com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                string rxml = service.getAccounts();



                if (!rxml.Equals("") || rxml != null)
                {
                    dsacc = Utility.getAccounts(rxml);

                    for (int ii = 0; ii <= (dsacc.Tables[0].Rows.Count - 1); ii++)
                    {
                        string nombre = dsacc.Tables[0].Rows[ii][1].ToString();

                        if (nombre.ToUpper().Equals(datos.strC7.ToUpper()))
                        {
                            account = dsacc.Tables[0].Rows[ii][0].ToString();

                        }


                    }
                }

                //ahora creo la transaccion
                comm.Parameters.Clear();
                comm.CommandText = " INSERT INTO tbl_paypal_tran  (pay_tran_reference, pay_tran_date, pay_tran_client,pay_tran_company, pay_tran_account, pay_trandate_process,pay_deppay_id, pay_tran_amount, pay_tran_receipt) values (@ref,getdate(), @client, @company, @acc, getdate(), @depid, @amount, @rec) ";
                comm.Parameters.Add("@ref", SqlDbType.VarChar).Value = datos.strC4;
                comm.Parameters.Add("@client", SqlDbType.VarChar).Value = datos.strC7;
                comm.Parameters.Add("@company", SqlDbType.Int).Value = 1;
                comm.Parameters.Add("@acc", SqlDbType.Int).Value = account;
                comm.Parameters.Add("@depid", SqlDbType.VarChar).Value = depid;
                comm.Parameters.Add("@amount", SqlDbType.Money).Value = datos.strC2;
                comm.Parameters.Add("@rec", SqlDbType.VarChar).Value = "AUTO PAYPAL";

                Utility.writeError("Paypal parametros transaccion ref" + datos.strC4 + "&client:" + datos.strC7 + "&acc:" + account + "&depid:" + depid + "&amount:" + datos.strC2);

                comm.ExecuteNonQuery();
                comm.Parameters.Clear();
                Utility.writeError("Paypal inserto transacion");
                //obtengo el numero de la transaccion creada
                comm.CommandText = "  SELECT   CONVERT(int,MAX(pay_tranid))   FROM  tbl_paypal_tran  ";
                reader = comm.ExecuteReader();

                while (reader.Read())
                {
                    if (!reader.IsDBNull(0)) tranid = reader.GetInt32(0);//pay_tranid

                }
                comm.Parameters.Clear();
                reader.Close();
                Utility.writeError("Paypal el id de la transaccion es:" + tranid);
                //agrego cada orden a la transaccion

                if (tranid != 0)
                {
                   
                    // Utility.writeError("Items trae # ordesn " + orders + ", items " + temporders.Length.ToString());

                    for (int j = 0; j < temporders.Length; j++)
                    {

                        int bandera = 0;
                        comm.CommandText = " select paid from [order]  where order_id=@order";
                        comm.Parameters.Add("@order", SqlDbType.Int).Value = temporders[j];
                        reader = comm.ExecuteReader();

                        while (reader.Read())
                        {
                            if (!reader.IsDBNull(0))
                            {
                                string tt = reader.GetString(0);
                                if (tt.ToUpper().Equals("YES")) { bandera = 1; }
                            }//pay_tranid

                        }
                        comm.Parameters.Clear();
                        reader.Close();

                        if (bandera == 0)
                        {
                            //colocandola en tran y order
                            comm.CommandText = " INSERT INTO tlb_paytran_order  (payord_order, payord_tranid) values (@order,  @tranid) ";
                            comm.Parameters.Add("@order", SqlDbType.Int).Value = temporders[j];
                            comm.Parameters.Add("@tranid", SqlDbType.VarChar).Value = tranid;
                            comm.ExecuteNonQuery();
                            comm.Parameters.Clear();

                            //poniendo la orden pagada
                            comm.CommandText = " update [order] set paid='YES', paid_date=getdate() where order_id=@order";
                            comm.Parameters.Add("@order", SqlDbType.Int).Value = temporders[j];
                            comm.ExecuteNonQuery();
                            comm.Parameters.Clear();




                        }
                        else
                        {
                            string from = "lucianab@pacificstarfinancial.com";
                            string subject = "Error Automatic Paypal Paid Order Duplicate";
                            string to = "lucianab@pacificstarfinancial.com;victorr@vickocorp.com;";
                            string body = "Order id:  " + temporders[j] + " is paid, re-paid dont apply";
                            Utility.sendMail(from, to, subject, body, "");



                        }
                    }


                }
                transaction.Commit();
                result = 0;
                temporders = orders.Split(';');
                

                for (int j = 0; j < temporders.Length; j++)
                {
                    RE_GenericBean rc = new RE_GenericBean();
                    rc = DB.getOrden(int.Parse(temporders[j]));
                    string from = "contact@bpophotos.com";
                    string subject = "Paid Order: " + rc.strC39 + ". " + rc.strC5 + " " + rc.strC6 + " " + rc.strC7 + " " + rc.strC8 + " " + rc.strC9;
                    string to = "violetp@pacificstarfinancial.com";
                    Utility.sendMail(from, to, subject, subject, "");
                    Utility.writeError("Paypal pago reportado a Violeta");
                }
            }
           
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;

    }


    public static REPORTDS getAccountReport(string where, string period, string type, string style, int paid)
    {
        REPORTDS result = new REPORTDS();
        //DataSet result = new DataSet();
        RE_GenericBean temp;

        try
        {
            if (!where.Equals("")) { where = "where  " + where; }
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = " SELECT [ORDER].order_id, [ORDER].ordernum, [ORDER].stnum, [ORDER].stadd, [ORDER].company, [ORDER].account, [ORDER].paid, CASE WHEN tbl_cheque.chk_date IS NULL THEN CONVERT(varchar, tbl_paypal_tran.pay_tran_date) ELSE CONVERT(varchar, tbl_cheque.chk_date) END AS Date, tbl_cheque.chk_reference, CONVERT(varchar, tbl_cheque.chk_id) AS chkid, tbl_paypal_tran.pay_tran_reference, CONVERT(varchar, tbl_paypal_tran.pay_tranid) AS tranid, convert(varchar,[ORDER].status_id) AS status, [ORDER].client_id, CONVERT(varchar, [ORDER].fee),PRODUCT.initial  FROM [ORDER] INNER JOIN PRODUCT ON [ORDER].product_id = PRODUCT.product_id LEFT OUTER JOIN tlb_paytran_order ON [ORDER].order_id = tlb_paytran_order.payord_order LEFT OUTER JOIN tbl_cheque_orden ON [ORDER].order_id = tbl_cheque_orden.cor_order_id LEFT OUTER JOIN tbl_paypal_tran ON tlb_paytran_order.payord_tranid = tbl_paypal_tran.pay_tranid LEFT OUTER JOIN tbl_cheque ON tbl_cheque_orden.cor_chk_id = tbl_cheque.chk_id   " + where;


            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                temp = new RE_GenericBean();
                if (!reader.IsDBNull(0)) temp.intC1 = reader.GetInt32(0); // order_id
                if (!reader.IsDBNull(1)) temp.strC1 = reader.GetString(1); // ordernum
                if (!reader.IsDBNull(2)) temp.strC2 = reader.GetString(2); // stnum
                if (!reader.IsDBNull(3)) temp.strC3 = reader.GetString(3); // stadd
                if (!reader.IsDBNull(4)) temp.strC4 = reader.GetInt32(4).ToString(); // company
                if (!reader.IsDBNull(5)) temp.strC5 = reader.GetInt32(5).ToString(); // acc
                if (!reader.IsDBNull(6)) temp.strC6 = reader.GetString(6); // paid
                if (!reader.IsDBNull(7)) temp.strC7 = reader.GetString(7); // date
                if (!reader.IsDBNull(8)) temp.strC8 = reader.GetString(8); else temp.strC8 = "";// check reference
                if (!reader.IsDBNull(9)) temp.strC9 = reader.GetString(9); else temp.strC9 = "NULL";// check id
                if (!reader.IsDBNull(10)) temp.strC10 = reader.GetString(10); else temp.strC10 = "";// tran paypal reference
                if (!reader.IsDBNull(11)) temp.strC11 = reader.GetString(11); else temp.strC11 = "NULL";// tran paypal id
                if (!reader.IsDBNull(12)) temp.strC15 = reader.GetString(12); // status
                if (!reader.IsDBNull(13)) temp.strC16 = reader.GetString(13); // client_id
                if (!reader.IsDBNull(14)) temp.strC17 = reader.GetString(14); // fee
                if (!reader.IsDBNull(15)) temp.strC18 = reader.GetString(15); // typeorder



                //ahorita veo si tiene check reference envio este y su id, o la transaccion de paypal y su id

                if (temp.strC8 != "") { temp.strC12 = temp.strC8; temp.strC13 = temp.strC9; temp.strC14 = "CH"; }
                if (temp.strC10 != "") { temp.strC12 = temp.strC10; temp.strC13 = temp.strC11; temp.strC14 = "PP"; }
                //cambio account y company

                Utility.setVariablesSession();
                DataSet dscompany = (DataSet)HttpContext.Current.Session["companies"];
                DataSet dsaccounts = (DataSet)HttpContext.Current.Session["accounts"];
                DataSet dsuser = (DataSet)HttpContext.Current.Session["Usuarios"];
                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(temp.strC4.ToString()))
                        {
                            temp.strC4 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                if (dsaccounts != null)
                {
                    for (int ii = 0; ii <= (dsaccounts.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccounts.Tables[0].Rows[ii][0].ToString().Equals(temp.strC5.ToString()))
                        {
                            temp.strC5 = dsaccounts.Tables[0].Rows[ii][2].ToString();
                        }
                    }
                }
                if (dsuser != null)
                {
                    for (int ii = 0; ii <= (dsuser.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsuser.Tables[0].Rows[ii][0].ToString().Equals(temp.strC16.ToString()))
                        {
                            temp.strC16 = dsuser.Tables[0].Rows[ii][2].ToString() + " " + dsuser.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }
                object[] obj = { temp.intC1.ToString(), temp.strC1, temp.strC2, temp.strC3, temp.strC4, temp.strC5, temp.strC6, temp.strC7, temp.strC12, temp.strC13, temp.strC14, temp.strC15, temp.strC16, temp.strC17, temp.strC18 };
                result.Tables["order"].Rows.Add(obj);



            }
            reader.Close();
            comm.Parameters.Clear();
            conn.Close();

            result.Tables["datos"].Rows.Add(period, "", "", type, style, null);

        }
        catch (Exception e)
        {
            Utility.writeError("Error Fail Report " + e.Message + e.StackTrace);
            result = null;
        }


        return result;
    }

    public static REPORTDS getAccountReportCl(string where, string period, string type, string style, int paid)
    {
        REPORTDS result = new REPORTDS();
        //DataSet result = new DataSet();
        RE_GenericBean temp;

        try
        {
            if (!where.Equals("")) { where = "where  " + where; }
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = " SELECT [ORDER].order_id, [ORDER].ordernum, [ORDER].stnum, [ORDER].stadd, [ORDER].company, [ORDER].account, [ORDER].paid_client,  CONVERT(varchar, [ORDER].paid_client_date,101) AS Date,  convert(varchar,[ORDER].status_id) AS status, [ORDER].client_id, convert(varchar,case when  [ORDER].psfprice is null then 0 else [ORDER].psfprice end),PRODUCT.initial  FROM [ORDER] INNER JOIN PRODUCT ON [ORDER].product_id = PRODUCT.product_id    " + where;


            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                temp = new RE_GenericBean();
                if (!reader.IsDBNull(0)) temp.intC1 = reader.GetInt32(0); // order_id
                if (!reader.IsDBNull(1)) temp.strC1 = reader.GetString(1); // ordernum
                if (!reader.IsDBNull(2)) temp.strC2 = reader.GetString(2); // stnum
                if (!reader.IsDBNull(3)) temp.strC3 = reader.GetString(3); // stadd
                if (!reader.IsDBNull(4)) temp.strC4 = reader.GetInt32(4).ToString(); // company
                if (!reader.IsDBNull(5)) temp.strC5 = reader.GetInt32(5).ToString(); // acc
                if (!reader.IsDBNull(6)) temp.strC6 = reader.GetString(6); // paid_client
                if (!reader.IsDBNull(7)) temp.strC7 = reader.GetString(7); // paid_client_date
                if (!reader.IsDBNull(8)) temp.strC15 = reader.GetString(8); // status
                if (!reader.IsDBNull(9)) temp.strC16 = reader.GetString(9); // client_id
                if (!reader.IsDBNull(10)) temp.strC17 = reader.GetString(10);// psfprice
                if (!reader.IsDBNull(11)) temp.strC18 = reader.GetString(11); // typeorder



                //cambio account y company

                Utility.setVariablesSession();
                DataSet dscompany = (DataSet)HttpContext.Current.Session["companies"];
                DataSet dsaccounts = (DataSet)HttpContext.Current.Session["accounts"];
                DataSet dsuser = (DataSet)HttpContext.Current.Session["Usuarios"];
                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(temp.strC4.ToString()))
                        {
                            temp.strC4 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                if (dsaccounts != null)
                {
                    for (int ii = 0; ii <= (dsaccounts.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccounts.Tables[0].Rows[ii][0].ToString().Equals(temp.strC5.ToString()))
                        {
                            temp.strC5 = dsaccounts.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }
                if (dsuser != null)
                {
                    for (int ii = 0; ii <= (dsuser.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsuser.Tables[0].Rows[ii][0].ToString().Equals(temp.strC16.ToString()))
                        {
                            temp.strC16 = dsuser.Tables[0].Rows[ii][2].ToString() + " " + dsuser.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }
                object[] obj = { temp.intC1.ToString(), temp.strC1, temp.strC2, temp.strC3, temp.strC4, temp.strC5, temp.strC6, temp.strC7, temp.strC15, temp.strC16, temp.strC17, temp.strC18, "", "", "" };
                result.Tables["order"].Rows.Add(obj);



            }
            reader.Close();
            comm.Parameters.Clear();
            conn.Close();

            result.Tables["datos"].Rows.Add(period, "", "", type, style, null);

        }
        catch (Exception e)
        {
            Utility.writeError("Error Fail Report " + e.Message + e.StackTrace);
            result = null;
        }


        return result;
    }

    public static REPORTDS getAccountReportNP(string where, string period, string type, string style, int paid)
    {
        REPORTDS result = new REPORTDS();
        //DataSet result = new DataSet();
        RE_GenericBean temp;

        try
        {
            if (!where.Equals("")) { where = " and  " + where; }
            SqlConnection conn = null;
            conn = OpenConnection();
            SqlDataReader reader;
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = " SELECT [ORDER].order_id, [ORDER].ordernum,PRODUCT.initial , usuarios.dbo.tbl_account.acc_initial,  [ORDER].stnum+' '+[ORDER].stadd+' '+[ORDER].stcity+' '+[ORDER].zip address,    CONVERT(varchar,[ORDER].fee) BPOFee, CONVERT(varchar,[ORDER].psfprice) PsfFee,  ";
            comm.CommandText += "  CONVERT(varchar, [STATUS].name) status, case when ([ORDER].ord_resubmitteddate is NULL  ) then CONVERT(varchar, [ORDER].ord_submitted_date,101)  ELSE CONVERT(varchar, [ORDER].ord_resubmitteddate,101) END   , [order].paid, [ORDER].client_id, usuarios.dbo.tbl_compania.com_name, [ORDER].comments  FROM [BPOPhotos].[dbo].[ORDER], [BPOPhotos].[dbo].PRODUCT, [BPOPhotos].dbo.STATUS ,  usuarios.dbo.tbl_account, usuarios.dbo.tbl_compania where [ORDER].product_id = PRODUCT.product_id and ";
            comm.CommandText += " [ORDER].status_id = STATUS.status_id and usuarios.dbo.tbl_account.acc_id = [ORDER].account  and usuarios.dbo.tbl_compania.com_id=[ORDER].company   " + where + " order by 9 asc";


            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                temp = new RE_GenericBean();
                if (!reader.IsDBNull(0)) temp.intC1 = reader.GetInt32(0); // order_id
                if (!reader.IsDBNull(1)) temp.strC1 = reader.GetString(1); // ordernum
                if (!reader.IsDBNull(2)) temp.strC2 = reader.GetString(2); // prodct type
                if (!reader.IsDBNull(3)) temp.strC3 = reader.GetString(3); // account
                if (!reader.IsDBNull(4)) temp.strC4 = reader.GetString(4); // address
                if (!reader.IsDBNull(5)) temp.strC5 = reader.GetString(5); // bpofee
                if (!reader.IsDBNull(6)) temp.strC6 = reader.GetString(6); // psfprice
                if (!reader.IsDBNull(7)) temp.strC7 = reader.GetString(7); // status
                if (!reader.IsDBNull(8)) temp.strC8 = reader.GetString(8); else temp.strC8 = "";// submited date
                if (!reader.IsDBNull(9)) temp.strC9 = reader.GetString(9); else temp.strC9 = "NULL";// paid
                if (!reader.IsDBNull(10)) temp.strC10 = reader.GetString(10); //client
                if (!reader.IsDBNull(11)) temp.strC11 = reader.GetString(11); // company
                if (!reader.IsDBNull(12)) temp.strC12 = reader.GetString(12); // comments




                object[] obj = { temp.intC1.ToString(), temp.strC1, temp.strC2, temp.strC3, temp.strC4, temp.strC5, temp.strC6, temp.strC7, temp.strC8, temp.strC9, temp.strC10, temp.strC11, temp.strC12, temp.strC17, temp.strC18 };
                result.Tables["order"].Rows.Add(obj);



            }
            reader.Close();
            comm.Parameters.Clear();
            conn.Close();

            result.Tables["datos"].Rows.Add(period, "", "", type, style, null);

        }
        catch (Exception e)
        {
            Utility.writeError("Error Fail Report " + e.Message + e.StackTrace);
            result = null;
        }


        return result;
    }
    public static RE_GenericBean intOrden(string table, string PK, string FK, int criterio)
    {
        RE_GenericBean intervalo = null;
        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        conn = OpenConnection2();
        transaction = conn.BeginTransaction();

        try
        {
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaction;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT  MIN(orden) AS Min, MAX(orden) AS Max  FROM  " + table + "  WHERE  (" + FK + " = (SELECT  " + FK + "  FROM  " + table + " AS tabla  WHERE  (" + PK + " = @criterio))) ";
            comm.Parameters.Add("@criterio", SqlDbType.Int).Value = criterio;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                intervalo = new RE_GenericBean();
                if (!reader.IsDBNull(0)) intervalo.intC1 = reader.GetInt32(0);//MIN
                if (!reader.IsDBNull(1)) intervalo.intC2 = reader.GetInt32(1);//MAX
            }
            comm.Parameters.Clear();
            reader.Close();

            transaction.Commit();
            return intervalo;
        }
        catch (Exception e)
        {
            transaction.Rollback();
            string ruta = "c:\\TEMP\\archivo.txt";
            StreamWriter escritor = new StreamWriter(ruta, true);
            escritor.WriteLine(e.Message.ToString());
            escritor.Close();
            return null;
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }

    }

    public static int getOppOrden(string table, string PK, int criterio, int orden, string FK, int query)
    {
        int result = 0, opcAnt = 0, ordAnt = 0;
        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        conn = OpenConnection2();
        transaction = conn.BeginTransaction();

        try
        {
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaction;
            comm.CommandType = CommandType.Text;

            int llave = 0;
            comm.CommandText = " SELECT   " + FK + "   FROM   " + table + "   WHERE   (" + PK + " = @criterio) ";
            comm.Parameters.Add("@criterio", SqlDbType.Int).Value = criterio;
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) llave = reader.GetInt32(0);//
            }
            comm.Parameters.Clear();
            reader.Close();

            //comm.CommandText = "SELECT mopc_id, orden FROM tbl_menu_opcion WHERE (mopc_id = (SELECT (SELECT TOP (1) mopc_id FROM tbl_menu_opcion AS tbl_menu_opcion_1 WHERE (orden < tabla.orden) AND (mopc_men_id = @fk) ORDER BY orden DESC) AS ordant FROM tbl_menu_opcion AS tabla WHERE (mopc_id = @criterio))) ";

            if (query == 0)//Si el cambio es para anterior
            {
                comm.CommandText = " SELECT " + PK + ", orden FROM " + table + " WHERE (" + PK + " = (SELECT (SELECT TOP (1) " + PK + " FROM " + table + " AS tabla2 WHERE (orden < tabla.orden) AND (" + FK + " = @fk) ORDER BY orden DESC) AS ordant FROM " + table + " AS tabla WHERE (" + PK + " = @criterio))) ";
            }
            else if (query == 1)//Si el cambio es para siguiente
            {
                comm.CommandText = " SELECT " + PK + ", orden FROM " + table + " WHERE (" + PK + " = (SELECT (SELECT TOP (1) " + PK + " FROM " + table + " AS tabla2 WHERE (orden > tabla.orden) AND (" + FK + " = @fk) ORDER BY orden) AS ordant FROM " + table + " AS tabla WHERE (" + PK + " = @criterio))) ";
            }
            comm.Parameters.Add("@criterio", SqlDbType.Int).Value = criterio;
            comm.Parameters.Add("@fk", SqlDbType.Int).Value = llave;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) opcAnt = reader.GetInt32(0);//idopcion
                if (!reader.IsDBNull(1)) ordAnt = reader.GetInt32(1);//orden
            }
            comm.Parameters.Clear();
            reader.Close();

            comm.CommandText = " UPDATE " + table + " SET orden = @orden WHERE (" + PK + " = @criterio) ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = ordAnt;
            comm.Parameters.Add("@criterio", SqlDbType.Int).Value = criterio;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();

            comm.CommandText = " UPDATE " + table + " SET orden = @orden WHERE (" + PK + " = @criterio) ";
            comm.Parameters.Add("@orden", SqlDbType.Int).Value = orden;
            comm.Parameters.Add("@criterio", SqlDbType.Int).Value = opcAnt;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();

            transaction.Commit();
            result = 1;
            return result;
        }
        catch (Exception e)
        {
            transaction.Rollback();
            string ruta = "c:\\TEMP\\archivo.txt";
            StreamWriter escritor = new StreamWriter(ruta, true);
            escritor.WriteLine(e.Message.ToString());
            escritor.Close();
            return 0;
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }

    }

    public static string getuin_ID(string userID, int tipo)
    {
        int uinID = 0;
        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        conn = OpenConnection2();
        transaction = conn.BeginTransaction();

        try
        {
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.Transaction = transaction;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT  uin_id  FROM  tbl_usuario_informacion  WHERE  (uin_usu_id = @user) AND (uin_tii_id = @type) ";
            comm.Parameters.Add("@user", SqlDbType.VarChar).Value = userID;
            comm.Parameters.Add("@type", SqlDbType.Int).Value = tipo;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) uinID = reader.GetInt32(0);
            }
            comm.Parameters.Clear();
            reader.Close();

            transaction.Commit();
            return uinID.ToString();
        }
        catch (Exception e)
        {
            transaction.Rollback();
            string ruta = "c:\\TEMP\\archivo.txt";
            StreamWriter escritor = new StreamWriter(ruta, true);
            escritor.WriteLine(e.Message.ToString());
            escritor.Close();
            return "0";
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }

    }


    public static DataSet GetOrderAccbyClient(string p)
    {//este metodo obtiene las ordenes que estan marcadas como pagadas por el cliente para su segunda contabilidad
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("Order #");//0
        result.Tables["Tabla"].Columns.Add("Status");// 2status order
        result.Tables["Tabla"].Columns.Add("Client");//3
        result.Tables["Tabla"].Columns.Add("Company");//4
        result.Tables["Tabla"].Columns.Add("Account");//5
        result.Tables["Tabla"].Columns.Add("Type");//5
        result.Tables["Tabla"].Columns.Add("Street");//6
        result.Tables["Tabla"].Columns.Add("Street Address");//7
        result.Tables["Tabla"].Columns.Add("Zip");//8
        result.Tables["Tabla"].Columns.Add("orderid");//9 yes or no
        result.Tables["Tabla"].Columns.Add("fee");//10 ord_failed_id
        result.Tables["Tabla"].Columns.Add("psffee");//11 yes o no
        result.Tables["Tabla"].Columns.Add("Paid");// 1status order
        result.Tables["Tabla"].Columns.Add("PaidDate");// 1status order
        result.Tables["Tabla"].Columns.Add("sum");// sumatoria acumulada fee
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            comm.CommandText = "SELECT  top 2000   [ORDER].ordernum, STATUS.name, [ORDER].client_id, [ORDER].company, [ORDER].account, PRODUCT.initial, [ORDER].stnum, [ORDER].stadd, [ORDER].zip, [ORDER].order_id, CONVERT(varchar(10), [ORDER].fee) AS fee, CONVERT(varchar(10), [ORDER].psfprice) AS psfprice,  case when [ORDER].paid_client='YES' then 'true' else 'false' end, CONVERT(varchar(10), [ORDER].paid_client_date, 101) AS client_date FROM  [ORDER] INNER JOIN   PRODUCT ON [ORDER].product_id = PRODUCT.product_id INNER JOIN  STATUS ON [ORDER].status_id = STATUS.status_id WHERE  ([ORDER].client_id = @client) order by [order].duedate desc";
            comm.Parameters.Add("@client", SqlDbType.VarChar).Value = p;
            reader = comm.ExecuteReader();
            RE_GenericBean rgb = null;
            double sum = 0;
            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.strC1 = reader.GetString(0); //orden#
                if (!reader.IsDBNull(1)) rgb.strC3 = reader.GetString(1).ToString();//status name
                if (!reader.IsDBNull(2)) rgb.strC4 = reader.GetString(2);//client
                if (!reader.IsDBNull(3)) rgb.strC5 = reader.GetInt32(3).ToString();//company
                if (!reader.IsDBNull(4)) rgb.strC6 = reader.GetInt32(4).ToString();//account
                if (!reader.IsDBNull(5)) rgb.strC7 = reader.GetString(5);//product name
                if (!reader.IsDBNull(6)) rgb.strC8 = reader.GetString(6);//st num
                if (!reader.IsDBNull(7)) rgb.strC9 = reader.GetString(7);//st address
                if (!reader.IsDBNull(8)) rgb.strC10 = reader.GetString(8);//zip
                if (!reader.IsDBNull(9)) rgb.intC1 = reader.GetInt32(9);//company
                if (!reader.IsDBNull(10)) rgb.strC11 = reader.GetString(10).ToString(); //fee
                if (!reader.IsDBNull(11)) rgb.strC12 = reader.GetString(11);  //psfprice
                if (!reader.IsDBNull(12)) rgb.strC13 = reader.GetString(12);  //paid
                if (!reader.IsDBNull(13)) rgb.strC14 = reader.GetString(13);  //paid date
                double temp = double.Parse(rgb.strC11);
                sum = sum + temp;
                rgb.strC15 = sum.ToString();

                Utility.setVariablesSession();
                DataSet dscompany = (DataSet)HttpContext.Current.Session["companies"];
                DataSet dsaccounts = (DataSet)HttpContext.Current.Session["accounts"];
                //buscando la compania
                if (dscompany != null)
                {
                    for (int ii = 0; ii <= (dscompany.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dscompany.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC5.ToString()))
                        {
                            rgb.strC5 = dscompany.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                if (dsaccounts != null)
                {
                    for (int ii = 0; ii <= (dsaccounts.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsaccounts.Tables[0].Rows[ii][0].ToString().Equals(rgb.strC6.ToString()))
                        {
                            rgb.strC6 = dsaccounts.Tables[0].Rows[ii][1].ToString();
                        }
                    }
                }

                object[] objArr = { rgb.strC1, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.intC1, rgb.strC11, rgb.strC12, rgb.strC13, rgb.strC14, rgb.strC15 };
                result.Tables["Tabla"].Rows.Add(objArr);
            }
            conn.Close();

        }
        catch (Exception e)
        {
            Utility.writeError(e.StackTrace + e.Message);
            return null;
        }
        return result;
    }

    public static ArrayList hasOld(int orden, string stnum, string zip, string city, string stadd, string unit)
    {
        RE_GenericBean result = new RE_GenericBean();
        ArrayList res = new ArrayList();

        SqlConnection conn = null;
        conn = OpenConnection();
        SqlCommand comm = null;
        SqlDataReader reader = null;


        try
        {
            comm = new SqlCommand();
            comm.Connection = conn;
            //Si son exactamente iguales
            comm.CommandType = CommandType.Text;
            string cond_unit = " and unit=@unit ";
            if (unit.Equals("")) { cond_unit = " and ( unit='' or unit is null )"; }
            comm.CommandText = " SELECT order_id, ordernum, stnum, stadd, unit, stcity, zip   FROM  [ORDER]  WHERE  stnum= @stnum and zip=@zip and stcity=@city and stadd=@stadd " + cond_unit + " and order_id<>@order  and status_id<>4 order by order_id ";
            comm.Parameters.Add("@order", SqlDbType.Int).Value = orden;
            comm.Parameters.Add("@stnum", SqlDbType.VarChar).Value = stnum;
            comm.Parameters.Add("@zip", SqlDbType.VarChar).Value = zip;
            comm.Parameters.Add("@city", SqlDbType.VarChar).Value = city;
            comm.Parameters.Add("@stadd", SqlDbType.VarChar).Value = stadd;
            comm.Parameters.Add("@unit", SqlDbType.VarChar).Value = unit;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                result = new RE_GenericBean();
                if (!reader.IsDBNull(0))
                {

                    result.intC1 = 1;//1 si es igual igual (stnum, stadd,unit ,city,zip)
                    // if (!result.strC2.Equals("")) result.strC2 += ";";
                    result.strC2 += reader.GetInt32(0).ToString();

                }
                if (!result.strC3.Equals("")) result.strC3 += ";";
                /* if (!reader.IsDBNull(1)) //ordernum
                 {
                    
                     result.strC3 += reader.GetString(1).ToString();

                 }*/
                if (!reader.IsDBNull(2)) result.strC3 += " " + reader.GetString(2).ToString();//stnum
                if (!reader.IsDBNull(3)) result.strC3 += " " + reader.GetString(3).ToString();//stadd
                if (!reader.IsDBNull(4)) result.strC3 += " " + reader.GetString(4).ToString();//unit
                if (!reader.IsDBNull(5)) result.strC3 += " " + reader.GetString(5).ToString();//city
                if (!reader.IsDBNull(6)) result.strC3 += " " + reader.GetString(6).ToString();//zipcode
                res.Add(result);
            }
            comm.Parameters.Clear();
            reader.Close();

            //Si son iguales menos en la unidad
            comm.CommandType = CommandType.Text;
            cond_unit = " and (unit<>@unit or stadd<>@stadd )";
            comm.CommandText = " SELECT order_id, ordernum,stnum, stadd, unit, stcity, zip   FROM  [ORDER]  WHERE  stnum= @stnum and zip=@zip and stcity=@city " + cond_unit + " and order_id<>@order  and status_id<>4 order by order_id ";
            comm.Parameters.Add("@order", SqlDbType.Int).Value = orden;
            comm.Parameters.Add("@stnum", SqlDbType.VarChar).Value = stnum;
            comm.Parameters.Add("@zip", SqlDbType.VarChar).Value = zip;
            comm.Parameters.Add("@city", SqlDbType.VarChar).Value = city;
            comm.Parameters.Add("@stadd", SqlDbType.VarChar).Value = stadd;
            comm.Parameters.Add("@unit", SqlDbType.VarChar).Value = unit;

            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                result = new RE_GenericBean();
                if (!reader.IsDBNull(0))
                {

                    result.intC1 = 3;//3 si es igual igual (stnum ,city,zip) menos unidad
                    //if (!result.strC2.Equals("")) result.strC2 += ";<br>";
                    result.strC2 += reader.GetInt32(0).ToString();

                }
                if (!result.strC3.Equals("")) result.strC3 += ";";
                /* if (!reader.IsDBNull(1)) //ordernum
                 {
                    
                     result.strC3 += reader.GetString(1).ToString();

                 }*/
                if (!reader.IsDBNull(2)) result.strC3 += " " + reader.GetString(2).ToString();//stnum
                if (!reader.IsDBNull(3)) result.strC3 += " " + reader.GetString(3).ToString();//stadd
                if (!reader.IsDBNull(4)) result.strC3 += " " + reader.GetString(4).ToString();//unit
                if (!reader.IsDBNull(5)) result.strC3 += " " + reader.GetString(5).ToString();//city
                if (!reader.IsDBNull(6)) result.strC3 += " " + reader.GetString(6).ToString();//zipcode
                res.Add(result);
            }
            comm.Parameters.Clear();
            reader.Close();



        }
        catch (Exception ex)
        {
            Utility.writeError(ex.Message + ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Close();

        }
        return res;
    }

    public static int comprobarZipCobertura(string p)
    {
        int result = 0;
        ArrayList res = new ArrayList();

        SqlConnection conn = null;
        conn = OpenConnection();
        SqlCommand comm = null;
        SqlDataReader reader = null;
        comm = new SqlCommand();
        comm.Connection = conn;

        comm.CommandType = CommandType.Text;
        comm.CommandText = "select   enable from ZIPCODE where zipcode = @zipcode ";
        comm.Parameters.Add("@zipcode", SqlDbType.VarChar).Value = p;
        reader = comm.ExecuteReader();

        while (reader.Read())
        {
            if (!reader.IsDBNull(0)) result = reader.GetInt32(0);
        }



        return result;
    }

    public static DataSet getUsuariosInactivos()
    {
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("id");
        result.Tables["Tabla"].Columns.Add("alias");
        result.Tables["Tabla"].Columns.Add("perfil");
        result.Tables["Tabla"].Columns.Add("nombre");
        result.Tables["Tabla"].Columns.Add("apellido");
        result.Tables["Tabla"].Columns.Add("perfil_nombre");

        try
        {
            conn = OpenConnection2();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " SELECT tbl_usuario.usu_id, tbl_usuario.usu_alias, tbl_usuario_perfil.upe_per_id, tbl_usuario.usu_nombre, tbl_usuario.usu_apellido, tbl_perfil.per_nombre ";
            comm.CommandText += " FROM  tbl_usuario INNER JOIN tbl_usuario_perfil ON tbl_usuario.usu_id = tbl_usuario_perfil.upe_usu_id INNER JOIN tbl_perfil ON tbl_usuario_perfil.upe_per_id = tbl_perfil.per_id ";
            comm.CommandText += " WHERE (tbl_usuario.usu_estado = 0) AND (tbl_perfil.per_catalogo = 1) ORDER BY tbl_usuario.usu_id ";
            reader = comm.ExecuteReader();

            RE_GenericBean usu;
            while (reader.Read())
            {
                usu = new RE_GenericBean();
                if (!reader.IsDBNull(0)) usu.strC1 = reader.GetString(0);
                if (!reader.IsDBNull(1)) usu.strC2 = reader.GetString(1);
                if (!reader.IsDBNull(2)) usu.intC1 = reader.GetInt32(2);
                if (!reader.IsDBNull(3)) usu.strC3 = reader.GetString(3);
                if (!reader.IsDBNull(4)) usu.strC4 = reader.GetString(4);
                if (!reader.IsDBNull(5)) usu.strC5 = reader.GetString(5);
                object[] objarr = { usu.strC1, usu.strC2, usu.intC1, usu.strC3, usu.strC4, usu.strC5 };
                result.Tables["Tabla"].Rows.Add(objarr);
            }
        }
        catch (Exception e)
        {
            string ruta = "c:\\TEMP\\archivo.txt";
            StreamWriter escritor = new StreamWriter(ruta, true);
            escritor.WriteLine(e.Message.ToString());
            escritor.Close();
            return null;
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }




    public static double getCityExtraFee(string p)
    {

        double result = 0;
        SqlConnection conn = null;
        conn = OpenConnection();
        SqlCommand comm = null;
        SqlDataReader reader = null;
        comm = new SqlCommand();
        comm.Connection = conn;
        try
        {
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select   fee from city_extrafee where city = @city ";
            comm.Parameters.Add("@city", SqlDbType.Int).Value = p;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) result = Double.Parse(reader.GetDecimal(0).ToString());
            }

        }
        catch (Exception ex)
        {
            Utility.writeError(ex.Message +" citie : "+p+ ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Close();

        }
        return result;
    }

    public static int coverageCityProduct(string city, int product, int company)
    {
        int result = 1;
        SqlConnection conn = null;
        conn = OpenConnection();
        SqlCommand comm = null;
        SqlDataReader reader = null;
        comm = new SqlCommand();
        comm.Connection = conn;
        try
        {
            comm.CommandType = CommandType.Text;
            int temp = 1;

            comm.CommandText = " select enable from city_product_coverage where city_id=@city and product_id=@product and company=@company";
            comm.Parameters.Add("@city", SqlDbType.Int).Value = city;
            comm.Parameters.Add("@product", SqlDbType.Int).Value = product;
            comm.Parameters.Add("@company", SqlDbType.Int).Value = company;
            Utility.writeError("Select OrderPlace" + comm.CommandText + "city: " + city + " product: "+product+ "company: " + company);
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                if (!reader.IsDBNull(0)) result = reader.GetInt32(0);

            }



        }
        catch (Exception ex)
        {
            Utility.writeError(ex.Message + ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Close();

        }
        return result;
    }
    public static int insertPhotos(RE_GenericBean r)
    {
        int result = 0;
        SqlConnection conn = null;
        conn = OpenConnection();
        SqlCommand comm = null;
        SqlDataReader reader = null;
        comm = new SqlCommand();
        comm.Connection = conn;
        try
        {
            comm.CommandType = CommandType.Text;



            comm.CommandText = " MERGE PHOTOS   ";
            comm.CommandText += " USING (SELECT @id AS ID1) AS EX ON (EX.ID1 = PHOTOS.id) ";
            comm.CommandText += " WHEN MATCHED THEN ";
            comm.CommandText += " UPDATE SET photos_received=@pr, complete_set=@cs, damages=@d, exteriorphotos=@ep, exteriordriver=@ed, photosreceivedate= @prd, uploadby=@up, uploaddate= @update, uploadtime=@uptime, status=@status ";
            comm.CommandText += " WHEN NOT MATCHED THEN ";
            comm.CommandText += " INSERT (photos_received,complete_set,damages,exteriorphotos, exteriordriver, photosreceivedate, uploadby, uploaddate, uploadtime, status) VALUES (@pr, @cs, @d, @ep, @ed, @prd, @up, @update, @uptime, @status); ";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = r.intC1;
            comm.Parameters.Add("@pr", SqlDbType.Int).Value = r.strC1;
            comm.Parameters.Add("@cs", SqlDbType.Int).Value = r.strC2;
            comm.Parameters.Add("@d", SqlDbType.VarChar).Value = r.strC3;
            comm.Parameters.Add("@ep", SqlDbType.VarChar).Value = r.strC4;
            comm.Parameters.Add("@ed", SqlDbType.VarChar).Value = r.strC5;
            comm.Parameters.Add("@prd", SqlDbType.VarChar).Value = r.strC6;
            comm.Parameters.Add("@up", SqlDbType.VarChar).Value = r.strC7;
            comm.Parameters.Add("@update", SqlDbType.VarChar).Value = r.strC8;
            comm.Parameters.Add("@uptime", SqlDbType.VarChar).Value = r.strC9;
            comm.Parameters.Add("@status", SqlDbType.Int).Value = r.intC2;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();

        }
        catch (Exception ex)
        {
            Utility.writeError(ex.Message + ex.StackTrace);

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Close();

        }
        return result;


    }

    public static DataSet getZibyCity(string city)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("zipcode");//zipcode
        result.Tables["Tabla"].Columns.Add("area");//area
        result.Tables["Tabla"].Columns.Add("city");//city
        result.Tables["Tabla"].Columns.Add("enable");//enable
        RE_GenericBean rg;
        SqlCommand comm = null;

        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT  zipcode, area_id, city,  enable FROM  ZIPCODE wHERE   city=@city  ";
            comm.Parameters.Add("@city", SqlDbType.Int).Value = city;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rg = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rg.intC1 = reader.GetInt32(0);//zipcode
                if (!reader.IsDBNull(1)) rg.intC2 = reader.GetInt32(1);//area
                if (!reader.IsDBNull(2)) rg.intC3 = reader.GetInt32(2);//city
                if (!reader.IsDBNull(3)) rg.intC4 = reader.GetInt32(3);//enable



                object[] objarr = { rg.intC1, rg.intC2, rg.intC3, rg.intC4 };
                result.Tables["Tabla"].Rows.Add(objarr);

            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();

        }



        return result;
    }


    public static void setCompsDNS(int order_id, string user_id, string doc1, string doc2, string doc3, string doc4)
    {
        SqlCommand comm = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " INSERT INTO  tbl_comps_dns  (order_id, processedby, document1, document2, document3, document4) VALUES (@ordid, @proc, @doc1, @doc2, @doc3, @doc4) ";
            comm.Parameters.Add("@ordid", SqlDbType.Int).Value = order_id;
            comm.Parameters.Add("@proc", SqlDbType.VarChar).Value = user_id;
            comm.Parameters.Add("@doc1", SqlDbType.VarChar).Value = doc1;
            comm.Parameters.Add("@doc2", SqlDbType.VarChar).Value = doc2;
            comm.Parameters.Add("@doc3", SqlDbType.VarChar).Value = doc3;
            comm.Parameters.Add("@doc4", SqlDbType.VarChar).Value = doc4;
            comm.ExecuteNonQuery();
            comm.Parameters.Clear();
        }
        catch (Exception ex)
        {
            Utility.writeError("Fail on insert comps dns " + ex.Message + ex.StackTrace);
        }
        finally
        {
            if (conn != null)
                conn.Close();
        }
    }


    public static int deleteCompsDoc(int orderid)
    {
        int result = 0;

        RE_GenericBean rg;
        SqlCommand comm = null;

        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT document2  FROM comparables  wHERE   order_id< @orderid  ";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orderid;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rg = new RE_GenericBean();
                if (!reader.IsDBNull(0))
                {
                    rg.strC1 = reader.GetString(0);//document2
                    string ruta = HttpContext.Current.Server.MapPath("~//data/comps/") + rg.strC1;
                    if (File.Exists(ruta))
                    {
                        string ruta2 = HttpContext.Current.Server.MapPath("~//data/compscopy/") + rg.strC1;
                        File.Move(ruta, ruta2);
                        // File.Delete(ruta);
                    }

                }



            }

            result = 1;
        }
        catch (Exception ex)
        {
            result = 0;

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();

        }



        return result;

    }

    public static int deleteSubsDoc(int orderid)
    {
        int result = 0;

        RE_GenericBean rg;
        SqlCommand comm = null;

        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "select  documentsub from QCSUB where order_id<@orderid  ";
            comm.Parameters.Add("@orderid", SqlDbType.Int).Value = orderid;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rg = new RE_GenericBean();
                if (!reader.IsDBNull(0))
                {
                    rg.strC1 = reader.GetString(0);//documentSub
                    string ruta = HttpContext.Current.Server.MapPath("~//data/subs/") + rg.strC1;
                    if (File.Exists(ruta))
                    {
                        string ruta2 = HttpContext.Current.Server.MapPath("~//data/subscopy/") + rg.strC1;
                        File.Move(ruta, ruta2);
                        //File.Delete(ruta);
                    }

                }



            }

            result = 1;
        }
        catch (Exception ex)
        {
            result = 0;

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();

        }



        return result;

    }

    public static DataSet getZipCoverage(string where)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("zipcode");//zipcode
        result.Tables["Tabla"].Columns.Add("area");//area
        result.Tables["Tabla"].Columns.Add("city");//city
        result.Tables["Tabla"].Columns.Add("enable");//enable
        result.Tables["Tabla"].Columns.Add("city_id");//city_id
        RE_GenericBean rg;
        SqlCommand comm = null;

        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = "SELECT  zipcode, area_id, c.name,  enable, zipcode.city FROM  ZIPCODE, CITY c WHERE  zipcode.city= c.city_id  " + where + " order by zipcode ";
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rg = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rg.intC1 = reader.GetInt32(0);//zipcode
                if (!reader.IsDBNull(1)) rg.intC2 = reader.GetInt32(1);//area
                if (!reader.IsDBNull(2)) rg.strC1 = reader.GetString(2);//city
                if (!reader.IsDBNull(3)) rg.intC4 = reader.GetInt32(3);//enable
                if (!reader.IsDBNull(4)) rg.intC5 = reader.GetInt32(4);//city_id



                object[] objarr = { rg.intC1, rg.intC2, rg.strC1, rg.intC4, rg.intC5 };
                result.Tables["Tabla"].Rows.Add(objarr);

            }


        }
        catch (Exception ex)
        {
            result = null;

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();

        }



        return result;
    }

    public static int updateZipcodeCoverage(ArrayList list)
    {
        int result = 1;
        SqlCommand comm = null;

        SqlDataReader reader = null;
        SqlConnection conn = null;
        SqlTransaction transaccion = null;
        try
        {



            comm = new SqlCommand();

            conn = OpenConnection();
            comm.Connection = conn;
            transaccion = conn.BeginTransaction();
            comm.CommandType = CommandType.Text;
            comm.Transaction = transaccion;
            foreach (RE_GenericBean rgzip in list)
            {



                comm.CommandText = "update zipcode set  enable=@enable where zipcode=@zip and city=@city  ";
                comm.Parameters.Add("@enable", SqlDbType.Int).Value = rgzip.intC1;
                comm.Parameters.Add("@zip", SqlDbType.Int).Value = rgzip.strC1;
                comm.Parameters.Add("@city", SqlDbType.Int).Value = rgzip.strC2;
                comm.ExecuteNonQuery();
                comm.Parameters.Clear();
                result = result * 1;
            }
            transaccion.Commit();
        }
        catch (Exception ex)
        {
            Utility.writeError("Error update zipcode coverage " + ex.Message + ex.StackTrace);
            result = result * 0;
            transaccion.Rollback();
        }
        finally
        {

            if (conn != null) conn.Close();
        }

        return result;
    }

    public static DataTable getArrLoginAcc(string where)
    {

        DataTable result = new DataTable();
        result.Columns.Add("id");
        result.Columns.Add("company");
        result.Columns.Add("name");
        result.Columns.Add("user");
        result.Columns.Add("pass");
        result.Columns.Add("mail");
        result.Columns.Add("address");
        result.Columns.Add("phone");
        result.Columns.Add("licence");
        result.Columns.Add("expiration");
        result.Columns.Add("eo");
        result.Columns.Add("expiration2");
        result.Columns.Add("w9");
        result.Columns.Add("companyid");
        result.Columns.Add("nameid");
        RE_GenericBean rgb = null;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection2();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            if (!where.Equals("")) { where = " where " + where; }
            comm.CommandText = " SELECT  l.id, c.com_name, tbl_agent.ag_name, l.acc_user, l.acc_pass, tbl_agent.ag_email, l.acc_address, l.acc_phone, l.acc_licence, l.acc_expiration, l.acc_eo, l.acc_expiration2, l.acc_w9, c.com_id,tbl_agent.ag_id FROM  tbl_acc_login AS l INNER JOIN tbl_compania AS c ON l.company_id = c.com_id INNER JOIN  tbl_agent ON l.acc_name = tbl_agent.ag_id  " + where;
            // comm.Parameters.Add("@id", SqlDbType.Int).Value = id;
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//company
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//account name
                if (!reader.IsDBNull(3)) rgb.strC3 = reader.GetString(3);//user
                if (!reader.IsDBNull(4)) rgb.strC4 = reader.GetString(4);//pass
                if (!reader.IsDBNull(5)) rgb.strC5 = reader.GetString(5);//mail
                if (!reader.IsDBNull(6)) rgb.strC6 = reader.GetString(6);//address
                if (!reader.IsDBNull(7)) rgb.strC7 = reader.GetString(7);//phone
                if (!reader.IsDBNull(8)) rgb.strC8 = reader.GetString(8);//licence
                if (!reader.IsDBNull(9)) rgb.strC9 = reader.GetString(9);//expirtion
                if (!reader.IsDBNull(10)) rgb.strC10 = reader.GetString(10);//peo
                if (!reader.IsDBNull(11)) rgb.strC11 = reader.GetString(11);//expiration2
                if (!reader.IsDBNull(12)) rgb.strC12 = reader.GetString(12);//w9
                if (!reader.IsDBNull(13)) rgb.strC13 = reader.GetInt32(13).ToString();//companyid
                if (!reader.IsDBNull(14)) rgb.intC2 = reader.GetInt32(14);//agentid
                
                result.Rows.Add(rgb.intC1, rgb.strC1, rgb.strC2, rgb.strC3, rgb.strC4, rgb.strC5, rgb.strC6, rgb.strC7, rgb.strC8, rgb.strC9, rgb.strC10, rgb.strC11, rgb.strC12, rgb.strC13, rgb.intC2);

            }
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message.ToString());
            return null;
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }


    public static RE_GenericBean saveLogin(ArrayList array, string userid)
    {

        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlTransaction transaccion;

        conn = DB.OpenConnection2();
        transaccion = conn.BeginTransaction();
        SqlCommand comm;
        comm = new SqlCommand();
        comm.Connection = conn;
        comm.Transaction = transaccion;
        comm.CommandType = CommandType.Text;
        try
        {

            foreach (RE_GenericBean rg in array)
            {
               
                comm.CommandText = " MERGE tbl_acc_login   ";
                comm.CommandText += " USING (SELECT @id AS ID1) AS EX ON (EX.ID1 = tbl_acc_login.id) ";
                comm.CommandText += " WHEN MATCHED THEN ";
                comm.CommandText += " update  set acc_name=@name, acc_user=@user, acc_pass=@pass,  acc_address=@add, acc_phone=@phone, acc_licence=@license, acc_expiration=@exp, acc_eo=@eo, acc_expiration2=@exp2, acc_w9=@w, acc_resp=@resp ";
                comm.CommandText += " WHEN NOT MATCHED THEN ";
                comm.CommandText += " INSERT  (company_id, acc_name, acc_user, acc_pass,  acc_address, acc_phone, acc_licence, acc_expiration, acc_eo, acc_expiration2, acc_w9) VALUES (@company,@name, @user, @pass, @add, @phone, @license, @exp, @eo, @exp2, @w); ";
                comm.Parameters.Add("@id", SqlDbType.Int).Value = rg.intC1;
                comm.Parameters.Add("@company", SqlDbType.VarChar).Value = rg.intC2;
                comm.Parameters.Add("@name", SqlDbType.Int).Value = rg.intC3;
                comm.Parameters.Add("@user", SqlDbType.VarChar).Value = rg.strC3;
                comm.Parameters.Add("@pass", SqlDbType.VarChar).Value = rg.strC4;
                comm.Parameters.Add("@add", SqlDbType.VarChar).Value = rg.strC6;
                comm.Parameters.Add("@phone", SqlDbType.VarChar).Value = rg.strC7;
                comm.Parameters.Add("@license", SqlDbType.VarChar).Value = rg.strC8;
                comm.Parameters.Add("@exp", SqlDbType.VarChar).Value = rg.strC9;
                comm.Parameters.Add("@eo", SqlDbType.VarChar).Value = rg.strC10;
                comm.Parameters.Add("@exp2", SqlDbType.VarChar).Value = rg.strC11;
                comm.Parameters.Add("@w", SqlDbType.VarChar).Value = rg.strC12;
                comm.Parameters.Add("@resp", SqlDbType.VarChar).Value = userid;
                comm.ExecuteNonQuery();

                
                comm.Parameters.Clear();

            }
            result.intC1 = 1;
            transaccion.Commit();
        }

        catch (Exception e)
        {
            Utility.writeError(e.Message.ToString());
            result.intC1 = 0;
            result.strC1 = "Error. "+e.Message.ToString();
            
        }
        finally
        {

            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }

    public static RE_GenericBean saveAgent(ArrayList array, string userid)
    {

        RE_GenericBean result = new RE_GenericBean();
        SqlConnection conn = null;
        SqlTransaction transaccion;

        conn = DB.OpenConnection2();
        transaccion = conn.BeginTransaction();
        SqlCommand comm;
        comm = new SqlCommand();
        comm.Connection = conn;
        comm.Transaction = transaccion;
        comm.CommandType = CommandType.Text;
        try
        {

            foreach (RE_GenericBean rg in array)
            {

                comm.CommandText = " MERGE tbl_agent   ";
                comm.CommandText += " USING (SELECT @id AS ID1) AS EX ON (EX.ID1 = tbl_agent.ag_id) ";
                comm.CommandText += " WHEN MATCHED THEN ";
                comm.CommandText += " update  set ag_name=@name, ag_email=@email ";
                comm.CommandText += " WHEN NOT MATCHED THEN ";
                comm.CommandText += " INSERT  ( ag_name, ag_email ) VALUES (@name, @email); ";


                comm.Parameters.Add("@id", SqlDbType.Int).Value = rg.intC1;
                comm.Parameters.Add("@name", SqlDbType.VarChar).Value = rg.strC1;
                comm.Parameters.Add("@email", SqlDbType.VarChar).Value = rg.strC2;
               
                comm.ExecuteNonQuery();


                comm.Parameters.Clear();

            }
            result.intC1 = 1;
            transaccion.Commit();
        }

        catch (Exception e)
        {
            Utility.writeError(e.Message.ToString());
            result.intC1 = 0;
            result.strC1 = "Error. " + e.Message.ToString();

        }
        finally
        {

            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }
    public static int deleteCompany(int companyid)
    {
        int result = 0;

        RE_GenericBean rg;
        SqlCommand comm = null;

        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection2();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " delete from tbl_compania  wHERE   com_id =  @id  ";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = companyid;
            reader = comm.ExecuteReader();
            
            result = 1;
        }
        catch (Exception ex)
        {
            result = 0;

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();

        }



        return result;

    }

    public static DataTable getArrAgent(string where)
    {

        DataTable result = new DataTable();
        result.Columns.Add("id");
        result.Columns.Add("name");
        result.Columns.Add("mail");
       
        RE_GenericBean rgb = null;
        SqlConnection conn = null;
        SqlCommand comm = null;
        SqlDataReader reader = null;
        try
        {
            conn = OpenConnection2();
            comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;

            if (!where.Equals("")) { where = " where " + where; }
            comm.CommandText = " select ag_id, ag_name, ag_email from  tbl_agent   " + where;
            
            reader = comm.ExecuteReader();

            while (reader.Read())
            {
                rgb = new RE_GenericBean();
                if (!reader.IsDBNull(0)) rgb.intC1 = reader.GetInt32(0); //id
                if (!reader.IsDBNull(1)) rgb.strC1 = reader.GetString(1);//agent name
                if (!reader.IsDBNull(2)) rgb.strC2 = reader.GetString(2);//email
                           
                result.Rows.Add(rgb.intC1, rgb.strC1, rgb.strC2);

            }
        }
        catch (Exception e)
        {
            Utility.writeError(e.Message.ToString());
            return null;
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (comm != null)
                comm.Dispose();
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return result;
    }

    public static int deleteAgent(int agentid)
    {
        int result = 0;

        RE_GenericBean rg;
        SqlCommand comm = null;

        SqlDataReader reader = null;
        SqlConnection conn = null;
        comm = new SqlCommand();
        try
        {
            conn = OpenConnection2();
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = " delete from tbl_agent  wHERE   ag_id =  @id  ";
            comm.Parameters.Add("@id", SqlDbType.Int).Value = agentid;
            reader = comm.ExecuteReader();

            result = 1;
        }
        catch (Exception ex)
        {
            result = 0;

        }
        finally
        {
            if (conn != null) conn.Close();
            if (reader != null) reader.Dispose();

        }



        return result;

    }
}

